Alert Controller 中实现可编辑文本字输入框

转载:swift.gg

作者:Arthur Knopper,原文链接,原文日期:2015-12-21译者:pmst;校对:Cee;定稿:千叶知风

创建可以弹出Alert Controller的Button

Alert Controller 中实现可编辑文本字输入框_第1张图片
Paste_Image.png

这个Button叫“Log in”,autolayout布局就省略了。

连接Button和viewController

Alert Controller 中实现可编辑文本字输入框_第2张图片
Paste_Image.png

代码实现

@IBAction func login(sender: AnyObject) {
        //1.申明两个textField
        var usernameTextField: UITextField?
        var passwordTextField: UITextField?
        
        //2. 创建一个alertController
        let alertController = UIAlertController(title: "log in", message: "please enter your credentials", preferredStyle: UIAlertControllerStyle.Alert)
        
        //3. 创建一个在alertController的按钮,用来打印输入的username和password
        let loginAction = UIAlertAction(title: "log in", style: UIAlertActionStyle.Default) { (action) -> Void in
            if let username = usernameTextField?.text {
                print("username = \(username)")
            } else {
                print("no name entered")
            }
            
            if let password = passwordTextField?.text {
                print("password = \(password)")
            } else {
                print("No password entered")
            }
            
        }
        
        //4. 给alertController添加usernameTextField
        alertController.addTextFieldWithConfigurationHandler { (txtUsername) -> Void in
            usernameTextField = txtUsername
            usernameTextField!.placeholder = ""
            
        }
        
        //5. 给alertController添加usernameTextField
        alertController.addTextFieldWithConfigurationHandler { (txtPassword) -> Void in
            passwordTextField = txtPassword
            passwordTextField!.secureTextEntry = true
            passwordTextField!.placeholder = ""
            
        }
        
        //6. 给alertController添加按钮的action
        alertController.addAction(loginAction)
        
        //7. 弹出alertController
        self.presentViewController(alertController, animated: true, completion: nil)
    }

结果展示

Alert Controller 中实现可编辑文本字输入框_第3张图片
Paste_Image.png

你可能感兴趣的:(Alert Controller 中实现可编辑文本字输入框)