防止键盘自动出现在UIAlertController中

Kev*_*_TA 5 uitextfield uikeyboard ios swift uialertcontroller

UIAlertController在Swift中有一个(警报样式),一切正常.但是,UITextField我添加到它的是一个可选字段,用户无需输入文本.问题是当我显示时UIAlertController,键盘与默认选择的文本字段同时出现.除非用户点击,否则我不希望键盘出现UITextField.如何才能做到这一点?

    let popup = UIAlertController(title: "My title",
        message: "My message",
        preferredStyle: .Alert)
    popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in
        optionalTextField.placeholder = "This is optional"
    }
    let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in
        let optionalTextField = popup.textFields![0]
        let text = optionalTextField.text
        print(text)
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
    popup.addAction(cancelAction)
    popup.addAction(submitAction)
    self.presentViewController(popup, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

Med*_*ida 4

这应该可以解决问题:

让你的viewController符合UITextFieldDelegate

分配popup.textFields![0].delegateself

添加唯一标签popup.textFields![0](我在下面的示例中使用了 999)

实施这个

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
  if textField.tag == 999 {
    textField.tag = 0
    return false
  }else{
    return true
  }
}
Run Code Online (Sandbox Code Playgroud)

你的代码应该是这样的:

    let popup = UIAlertController(title: "My title",
                                  message: "My message",
                                  preferredStyle: .Alert)
    popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in
        optionalTextField.placeholder = "This is optional"
    }
    popup.textFields![0].delegate = self
    popup.textFields![0].tag = 999
    let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in
        let optionalTextField = popup.textFields![0]
        let text = optionalTextField.text
        print(text)
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
    popup.addAction(cancelAction)
    popup.addAction(submitAction)
    self.presentViewController(popup, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)