仅为特定的editText添加用于keyboardWasSn的NSNotificationCenter

时间:2014-09-06 22:04:38

标签: ios keyboard uitextfield uitextview nsnotificationcenter

在我的iOS应用中,我有一个带有textField和textView的视图,两者都是可编辑的:

enter image description here

我想只在用户点击textView(在底部)而不是textField时滚动视图。我在键盘出现时设置了通知:

[[NSNotificationCenter defaultCenter] addObserver:self
  selector:@selector(keyboardWasShown:)
  name:UIKeyboardDidShowNotification object:nil];

但无论触发了哪个字段,只要键盘出现就会触发此通知。 如何仅触发textField的通知?我尝试了以下操作:

[[NSNotificationCenter defaultCenter] addObserver:self.stepDescriptionField
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

但是当我点击textField时,我收到错误:

[UITextView keyboardWasShown:]: unrecognized selector sent to instance 0x13cd30950
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITextView keyboardWasShown:]: unrecognized selector sent to instance 0x13cd30950'

2 个答案:

答案 0 :(得分:1)

我认为您应该使用UITextViewDelegate协议而不是键盘通知,根据Apple文档,您应该使用此方法:

 - (void)textViewDidBeginEditing:(UITextView *)textView

“文本视图在用户在文本视图中启动编辑之后以及在实际进行任何更改之前立即将此消息发送给其委托”

作为一个例子:

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if (textView == self.stepDescriptionField) {
        [self.scrollView setContentOffset:CGPointMake(0 ,270) animated:YES];
    }
}

了解更多信息请查看Apple文档:

https://developer.apple.com/library/ios/documentation/uikit/reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html

答案 1 :(得分:0)

这就是我最终解决问题的方法:

我添加了通知程序:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification object:nil];

然后我使用textViewDidBeginEditing和textViewDidEndEditing来设置activeView:

// "Slides" screen up when textFields are being edited
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    NSLog(@"began editing textField");
    self.activeView = textView;
}

// "Slides" screen back down when textFields are no longer being edited
- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.activeView = nil;
}

然后在我的keyboardWasShown方法中,我在滚动之前检查了activeview的类:

if ( [NSStringFromClass(self.activeView.class) isEqualToString:@"UITextView"] && !CGRectContainsPoint(aRect, self.activeView.frame.origin) ) {
    NSLog(@"scrolling");
    CGPoint scrollPoint = CGPointMake(0.0, self.stepDescriptionField.frame.origin.y-kbSize.height);
    [self.scrollView setContentOffset:scrollPoint animated:YES];
}