UITextField失去焦点事件

问题描述:

我在MyCustomUIView类中有一个UITextField,当UITextField失去焦点时,我想隐藏该字段并显示其他位置。UITextField失去焦点事件

UITextField委托是通过IB设置为MyCustomUIView和我也有“真的结束退出时”和“编辑真的结束”事件中MyCustomUIView指向一个IBAction方法。

@interface MyCustomUIView : UIView { 

IBOutlet UITextField *myTextField; 

} 

-(IBAction)textFieldLostFocus:(UITextField *)textField; 

@end 

但是,当UITextField失去焦点时,这些事件似乎都不会被解雇。你如何捕捉/寻找这个事件?

UITextField的代表被设置为MyCustomUIView,所以我收到textFieldShouldReturn消息以在完成时关闭键盘。

但我也感兴趣的是确定当用户按下屏幕上的其他区域(说另一个控制或只是空白区域)和文本字段已失去焦点。

我相信你需要指定您的视图,就像这样的UITextField委托:

@interface MyCustomUIView : UIView <UITextFieldDelegate> { 

作为额外的奖励,你这是怎么弄的键盘时,他们按“完成”或回报走开按钮,这取决于你如何设置该属性:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { 
    //This line dismisses the keyboard.  
    [theTextField resignFirstResponder]; 
    //Your view manipulation here if you moved the view up due to the keyboard etc.  
    return YES; 
} 

您可能需要子类UITextField并覆盖resignFirstResponder。将调用resignFirstResponder就像文本字段失去焦点。

resignFirstResponder解决方案的问题仅仅是,它只能通过明确的键盘的UITextField事件触发。 我还在寻找一个“失去焦点的事件”来隐藏键盘,如果在文本框之外的某个地方被点击了。 我碰到的唯一贴近实用的“解决方案”是,为了禁止其他视图的交互,直到用户完成编辑(敲击完成/键盘上的返回),但仍然能够在文本域之间跳转以进行更正而不需要每次都滑出和键入。

下面的代码片段可能有用的人,谁愿意做同样的事情:

// disable all views but textfields 
// assign this action to all textfields in IB for the event "Editing Did Begin" 
-(IBAction) lockKeyboard : (id) sender { 

    for(UIView *v in [(UIView*)sender superview].subviews) 
     if (![v isKindOfClass:[UITextField class]]) v.userInteractionEnabled = NO; 
} 

// reenable interactions 
// assign this action to all textfields in IB for the event "Did End On Exit" 
-(IBAction) disMissKeyboard : (id) sender { 

    [(UIResponder*)sender resignFirstResponder]; // hide keyboard 

    for(UIView *v in [(UIView*)sender superview].subviews) 
     v.userInteractionEnabled = YES; 
} 

尝试使用委托下面的方法:

- (BOOL) textFieldShouldEndEditing:(UITextField *)textField { 
    NSLog(@"Lost Focus for content: %@", textField.text); 
    return YES; 
} 

为我工作。

我想你已经实现了UIKeyboardDidHideNotification,在这种情况下,您

使用如下代码

[theTextField resignFirstResponder]; 

删除此代码。

同样的代码写在textFieldShouldReturn方法。这也失去了重点。

对于那些在Swift中挣扎的人。我们在ViewController的视图中添加一个手势识别器,以便当视图被点击时,我们关闭文本框。不要取消对视图的后续点击很重要。

SWIFT 2.3

override func viewDidLoad() { 
     //..... 

     let viewTapGestureRec = UITapGestureRecognizer(target: self, action: #selector(handleViewTap(_:))) 
     //this line is important 
     viewTapGestureRec.cancelsTouchesInView = false 
     self.view.addGestureRecognizer(viewTapGestureRec) 

     //..... 
    } 

    func handleViewTap(recognizer: UIGestureRecognizer) { 
     myTextField.resignFirstResponder() 
    }