iOS 9(Swift 2) - resignFirstResponder()抛出错误

时间:2016-03-13 02:48:21

标签: ios swift

我有一个自定义视图,显示从UITextField输入的单词列表。

为了方便快捷地输入,我打算在按下返回键后不隐藏键盘,而是重置文本字段,让用户继续键入更多单词。当用户输入单词时,我需要隐藏键盘,这意味着当用户点击文本字段之外时。

但是当在文本字段之外点击时,以下实现给了我未捕获的异常。

我想知道与resignFirstResponder()关联的空字符串检查是否导致这种情况,但我需要确保该字段是否包含某些值。

我认为self.endEditing(true)与我的情况无关,因为除非在文本字段之外点击,否则无法知道用户何时想要结束编辑。

override func viewDidLoad() {

    super.viewDidLoad()

    textField.delegate = self
    textField.returnKeyType = UIReturnKeyType.Done

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    textField.resignFirstResponder()
}

func textFieldShouldReturn(textField: UITextField) -> Bool {

    if let text = textField.text {
        addTextToList()
    }
    textField.text = ""

    return true
}

未捕获的例外是

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CookMate.CreateRecipeVC ingredientTextFieldDidChange:]: unrecognized selector sent to instance 0x7f80f1de3370'

2 个答案:

答案 0 :(得分:1)

您是否通过故事板建立了一个出口,后来又删除了名为ingredientTextFieldDidChange的出口?右键单击故事板中的textField以查看是否存在,然后按x将其删除。

答案 1 :(得分:0)

你可以每次为我使用这种方法

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

您可能会发现它很有用。