2013-12-17 13 views
16

私はキーボードの外観イベントの通知を設定しました。では、UITextViewとUITextFieldについて考えてみましょう。UITextFieldとKeyboard Notifications - strange order

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

セレクタは:UITextView、デリゲート方法- (void)textViewDidBeginEditing:(UITextView *)textViewの場合

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

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

AFTER keyboardWillShow:方法発射されます。だからkeyboardSizeはキーボードの実際のサイズを持っており、私はそれをtextviewデリゲートメソッドの中で使うことができます。 UITextFieldの、対応するデリゲート方法- (void)textFieldDidBeginEditing:(UITextField *)textFieldの場合しかし

BEFORE keyboardWillShow:方法発射されます。

これはなぜですか?キーボードのCGSizeをテキストフィールドの場合は、テキストフィールドデリゲートが最初に呼び出され、キーボードセレクタは呼び出されないので、ゼロを返すようにするにはどうすればよいですか。

答えて

4

奇妙な... Appleの終わりに間違いのように聞こえる。

多分、キーボードのポップアップが遅れることがありますか?ここで私の残念ながら非常に面倒な "回避策"の提案 - あなたは、テキストフィールドが選択されたときに通知を送信することができますが、実際に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

質問はテキストフィールドに関するもので、テキストビューのデリゲートメソッドをお勧めします。私はそれを取得しない、何がポイントですか? – Andy

+0

答えはこの問題とは関係ないかもしれませんが、私の場合は問題を解決しました。ありがとう! –