当用户触发操作 sheet 并关闭它时,如何关闭文本字段上的键盘?

How to dismiss keyboard on a textfield when a user triggers an action sheet and dismisses it?

我有一个符合 UITextFieldDelegate

的 UITextField

@IBOutlet weak var myCoolTextField: UITextField!

我还有一个触发动作的按钮 sheet。

@IBAction func myCoolButton(sender: UIButton) {
  let alert = UIAlertController(title: "Hey", message: "Hey there", preferredStyle: .ActionSheet)
  let dismissAction = UIAlertAction(title: "Done", style: .Cancel, handler: nil)
  alert.addAction(dismissAction)
  self.presentViewController(alert, animated: true, completion: nil)
}

如果用户正在编辑 myCoolTextField,他们可以点击 myCoolButton 关闭键盘进行编辑 myCoolTextField 然后 UIAlertController 接管操作 sheet。当用户解除警报时,键盘会再次自动弹出并将用户带回编辑 myCoolTextField.

我将如何防止这种情况发生?如果用户在编辑 myCoolTextField 期间点击 myCoolButton 然后关闭警报,我不希望 myCoolTextField 自动返回编辑模式。

我有常规的旧 textFieldShouldReturntouchesBegan 方法,可用于点击屏幕上的其他任何地方。我已经尝试在 sheet 的完成处理程序的呈现中添加方法来结束 myCoolTextField 的编辑,但它没有做任何事情,因为那时键盘和文本字段暂时不可用积极的。有什么想法吗?

您可以使用 resignFirstResponder 方法关闭键盘:

@IBAction func myCoolButton(sender: UIButton) {
  myCoolTextField.resignFirstResponder()
  let alert = UIAlertController(title: "Hey", message: "Hey there", preferredStyle: .ActionSheet)
  let dismissAction = UIAlertAction(title: "Done", style: .Cancel, handler: nil)
  alert.addAction(dismissAction)
  self.presentViewController(alert, animated: true, completion: nil)
}