防止UIAlertController自动弹出键盘

5
我在Swift中有一个UIAlertController(警报样式),一切工作正常。但我添加到它的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)

2
你必须在其他地方进行makeFirstResponder调用。或者在弹出警告框之前/之后,你可以调用self.view endEditing:YES。 - Teja Nandamuri
2个回答

4
这样做应该会有帮助:
使您的视图控制器符合 UITextFieldDelegatepopup.textFields![0].delegate 指定为 selfpopup.textFields![0] 添加独特标记(在下面的示例中,我使用了 999)
实施此方法
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
  if textField.tag == 999 {
    textField.tag = 0
    return false
  }else{
    return true
  }
}

您的代码应该像这样:

    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)

3

我认为这是警告框中textField的默认行为,也许考虑一种替代设计,使得只有在必要时才会显示textField...

现在解决了这个问题,我们来绕过它!

当你添加textField时,将它的委托设置为viewController并为其添加一个标签。

例如:

popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in
    optionalTextField.placeholder = "This is optional"
    optionalTextField.delegate = self
    optionalTextField.tag = -1
}

然后实现textFieldShouldBeginEditing()方法

func textFieldShouldBeginEditing(textField: UITextField!) {   
    if textField.tag == -1 {
        textField.tag = 0
        return false
    } else {
        return true
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接