代码之家  ›  专栏  ›  技术社区  ›  Jake2Finn

正确使用UIViewController中的present

  •  0
  • Jake2Finn  · 技术社区  · 7 年前

    我遇到了一个问题,我不能在我的类中使用“self”呈现动态UIViewController。它告诉我“类型的值”(LoginScreenVC)->()->(LoginScreenVC)'没有成员“视图”。

    它将使用一个闭包,例如。 if let loginScreen = UIStoryBoard ... ,但由于要切换到的UIViewController是动态的,因此无法将其强制转换为特定的UIViewController。

    是否有其他方式显示ViewController?

    SWIFT 4.2/XCode 10.1

    import UIKit
    
    class LoginScreenVC: UIViewController {
        let myTokenHandler = TokenHandler()
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        @IBAction func loginButton(_ sender: Any) {
            print("Login button pressed")
    
            let usernameInputField = self.view.viewWithTag(6548) as! UITextField
            let passwordInputField = self.view.viewWithTag(6549) as! UITextField
    
            userInput = usernameInputField.text!
            passInput = passwordInputField.text!
    
            // call completion handler
            requestToken(success: handlerBlock)
    
        }
        // completion handler step 1: request token and get redirect string to switch screen
        func requestToken(success: (String) -> Void) {
            let requestResult = myTokenHandler.requestToken(password: passInput, username: userInput)
            success(requestResult)
        }
    
        // completion handler step 2: use redirect string to switch screen
        let handlerBlock: (String) -> Void = { redirect in
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let loginScreen = storyboard.instantiateViewController(withIdentifier: redirect)
                self.present(loginScreen, animated: true, completion: nil) //Value of type '(LoginScreenVC) -> () -> (LoginScreenVC)' has no member 'view'
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   matt    7 年前

    let handlerBlock: (String) -> Void = { redirect in
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let loginScreen = storyboard.instantiateViewController(withIdentifier: redirect)
        self.present(loginScreen, animated: true, completion: nil)
    }
    

    问题是你用的是这个词 self 在没有 自己 自己 present 是UIViewController实例方法,所以 自己

    我可以想出五六种方式来表达你想要表达的东西,但最简单的可能是将其改写为:

    func handlerBlock(_ redirect:String) -> Void {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let loginScreen = storyboard.instantiateViewController(withIdentifier: redirect)
        self.present(loginScreen, animated: true, completion: nil)
    }
    

    现在 handlerBlock 实例方法 自己 把手 requestToken(success: handlerBlock)