2013-12-17 13 views
16

所以我爲鍵盤外觀事件設置了一個通知。現在讓我們考慮一個UITextView和一個UITextField。UITextField和鍵盤通知 - 奇怪的順序

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardWillShow:) 
              name:UIKeyboardWillShowNotification 
              object:nil]; 

選擇器是:

- (void)keyboardWillShow:(NSNotification *)notification { 

     keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 
} 

在一個UITextView的情況下,所述委託方法- (void)textViewDidBeginEditing:(UITextView *)textView燒製AFTERkeyboardWillShow:方法。所以keyboardSize具有鍵盤的實際尺寸,我可以在textview委託方法中使用它。

但是在UITextField的情況下,相應的委託方法- (void)textFieldDidBeginEditing:(UITextField *)textField被觸發之前keyboardWillShow:方法。

這是爲什麼呢?如何在文本框的情況下獲取鍵盤的CGSize,因爲它現在只返回零,因爲文本字段委託首先被調用,而不是鍵盤選擇器。

回答

4

奇怪......聽起來像是蘋果公司的錯誤。

也許你可以延遲鍵盤彈出?這是我不幸的非常混亂的「解決方法」建議 - 您可以在選擇文本字段時發送通知,但實際上只是稍後開始編輯一小段時間,以便在調用keyboardWillShow:之前事實上已知文本字段。例如:

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

    // Notification corresponding to "textFieldSelected:" method 
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_TEXT_FIELD_SELECTED object:nil userInfo:[[NSDictionary alloc] initWithObjectsAndKeys:textField, @"textField", nil]]; 

    // "textFieldReallyShouldBeginEditing" is initially set as FALSE elsewhere in the code before the text field is manually selected 
    if (textFieldReallyShouldBeginEditing) 
     return YES; 
    else 
     return NO: 
} 

- (void)textFieldSelected:(NSNotification*)notification { 

    // Done in a separate method so there's a guaranteed delay and "textFieldReallyShouldBeginEditing" isn't set to YES before "textFieldShouldBeginEditing:" returns its boolean. 
    [self performSelector:@selector(startTextFieldReallyEditing:) withObject:(UITextField*)notification[@"textField"] afterDelay:.01]; 
} 

- (void)startTextFieldReallyEditing:(UITextField*)textField { 
    textFieldReallyShouldBeginEditing = YES; 

    // To trigger the keyboard 
    [textField becomeFirstResponder]; 
} 

然後根據您如何創建通知,您甚至可以在開始編輯之前插入此已知文本字段的值。

+1

在我的情況簡單dispatch_async(mainQueue,^ {})幫助。 – Andy

4

我有這個相同的問題。嘗試使用:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView    
+0

問題是關於textfield,你建議textview委託方法。我不明白,這有什麼意義? – Andy

+0

答案可能與這個問題無關,但它解決了我的情況。謝謝! –