2009-07-15 145 views
17

我在MyCustomUIView類中有一個UITextField,當UITextField失去焦點時,我想隱藏該字段並顯示其他位置。UITextField失去焦點事件

UITextField委託是通過IB設置爲MyCustomUIView和我也有「真的結束退出時」和「編輯真的結束」事件中MyCustomUIView指向一個IBAction方法。

@interface MyCustomUIView : UIView { 

IBOutlet UITextField *myTextField; 

} 

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

@end 

但是,當UITextField失去焦點時,這些事件似乎都不會被解僱。你如何捕捉/尋找這個事件?

UITextField的代表被設置爲MyCustomUIView,所以我收到textFieldShouldReturn消息以在完成時關閉鍵盤。

但我也感興趣的是確定當用戶按下屏幕上的其他區域(說另一個控制或只是空白區域)和文本字段已失去焦點。

回答

11

我相信你需要指定您的視圖,就像這樣的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; 
} 
2

您可能需要子類UITextField並覆蓋resignFirstResponder。將調用resignFirstResponder就像文本字段失去焦點。

4

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; 
} 
26

嘗試使用委託下面的方法:

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

爲我工作。

1

我想你已經實現了UIKeyboardDidHideNotification,在這種情況下,您

使用如下代碼

[theTextField resignFirstResponder]; 

刪除此代碼。

同樣的代碼寫在textFieldShouldReturn方法。這也失去了重點。

0

對於那些在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() 
    }