美文网首页iOS DeveloperiOS开发iOS 开发
Alert Controller 中实现可编辑文本字输入框

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

作者: Hollylord | 来源:发表于2016-01-04 15:15 被阅读1269次

    转载:swift.gg

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

    创建可以弹出Alert Controller的Button

    Paste_Image.png

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

    连接Button和viewController

    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 = "<Your username here>"
                
            }
            
            //5. 给alertController添加usernameTextField
            alertController.addTextFieldWithConfigurationHandler { (txtPassword) -> Void in
                passwordTextField = txtPassword
                passwordTextField!.secureTextEntry = true
                passwordTextField!.placeholder = "<your password here>"
                
            }
            
            //6. 给alertController添加按钮的action
            alertController.addAction(loginAction)
            
            //7. 弹出alertController
            self.presentViewController(alertController, animated: true, completion: nil)
        }
    

    结果展示

    Paste_Image.png

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/xifahttx.html