iOS:当UITextField失去焦点时关闭键盘

时间:2016-05-25 21:39:56

标签: ios cocoa-touch uitextfield

如何在键盘打开并关闭键盘时识别出其他视图被点击。另一个视图可以在父控制器或屏幕上显示的其他控制器中。

2 个答案:

答案 0 :(得分:0)

尝试在viewController的主视图上设置点击手势识别器。点击它时,请拨打view.endEditing(true)

如果您有其他手势识别器并且不想干扰它们,请尝试设置点击识别器,创建对它的引用(如果在故事板中执行),然后在textFieldDidBeginEditing设置要启用的识别器,并在textFieldDidEndEditing中将其设置为禁用。

典型代码片段:

class FakeViewController: UIViewController, UITextFieldDelegate {

    private let viewTappedGestureRecognizer = UITapGestureRecognizer()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupGestureRecognizer()
    }

    private func setupGestureRecognizer() {
        viewTappedGestureRecognizer.addTarget(self, action: #selector(viewWasTapped))
        view.addGestureRecognizer(viewTappedGestureRecognizer)
    }

    func viewWasTapped(sender: UITapGestureRecognizer) {
        view.endEditing(true)
    }


    // MARK: - TextField Delegate

    func textFieldDidBeginEditing(textField: UITextField) {
        viewTappedGestureRecognizer.enabled = true
    }

    func textFieldDidEndEditing(textField: UITextField) {
        viewTappedGestureRecognizer.enabled = false
    }

}

答案 1 :(得分:0)

因为在您的情况下,您可能在屏幕上显示多个viewController,处理此问题的最佳方法是使用Notification Pattern 通知当前Observer(customView或ViewControler)其textField / textView(即当前firstResponder即键盘显示)应resignFirstResponder(并关闭键盘) )。

注册以观察(TextField或TextView)BeginEditing中的任何DismissKeyboardNeededNotification:

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyboard) name:DismissKeyboardNeededNotification object:nil];
    return YES;
}

在EndEditing中删除Observer to Notification(DismissKeyboardNeededNotification)

-(void)textFieldDidEndEditing:(UITextField *)textField{

    [self.textField resignFirstResponder];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:DismissKeyboardNeededNotification object:nil];

}

如果当前的ViewController得到通知,那么只需要将textfield resignFirstResponder发送给dismissKeyboard

-(void)dismissKeyboard{

    [self.textField resignFirstResponder]; 
    //or if you have many textField/TextView find it resignFirstResponder
    //[self.textView1 isFirstResponder] then resignFirstResponder
}

来自任何viewController,当一个视图被录音/选中时(UITextView或UITextView除外)只是发布通知,要求dismissKeyboard,如果需要,如果键盘当前显示,那么你的一个ViewController正在观察该通知,它将被处理。

[[NSNotificationCenter defaultCenter] postNotificationName:DismissKeyboardNeededNotification object:nil userInfo:nil];

注意:所有VC都应该可以访问此公共字符串:

 NSString* DismissKeyboardNeededNotification = @"DismissKeyboardNeededNotification";