ios - 键盘隐藏通知调用多次

标签 ios objective-c iphone

Sir On Tap Gesture 我正在隐藏键盘。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

它们工作正常。但是当我们第二次编辑 textView 时。 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; 多次调用。他们在 keyboardWillBeHidden 中执行我的代码 5-6 次。当 textview 开始编辑时,他们以任何方式不调用。

- (void)textViewDidBeginEditing:(UITextView *)textView
{

    if ([textView.text isEqualToString:@"Type your message Here..."]) {
        textView.text = @"";
        textView.textColor = [UIColor grayColor]; //optional
    }

    [self scrollToBottomAnimated:YES];
  }
- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [tableViews numberOfRowsInSection:0];
    if(rows > 0) {
        [tableViews scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
                          atScrollPosition:UITableViewScrollPositionBottom
                                  animated:animated];
    }
}

最佳答案

这取决于您使用 NSNotificationCenter 注册键盘通知的位置和次数。

如果您在 View 中添加观察者将出现并在 View 中移除观察者将消失。

如果您在 viewdidload 中添加观察者,则在 dealloc 调用中移除观察者。

只需尝试更改您注册通知的位置即可。为确保只有 viewController 可见是接收通知的 Controller ,请在 vieWillAppear 中注册通知并在 viewWillDisappear 中删除通知。

这也将解决您多次调用代码的问题。

关于ios - 键盘隐藏通知调用多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32739449/

相关文章:

iphone - 是否可以追踪拨出电话和短信?

iphone - 键入时 UITextField 中的 EXC_BAD_ACCESS

iPhone 显示照片/图像滑动(如照片库和 Facebook 应用程序)?

ios - 自定义 CAGradientLayer 不设置动画

ios - 如何从我的应用程序注销并转到初始登录 View ?

ios - iOS 中的稀疏图像匹配

ios - 如何更改 viewController 的颜色(或主题)?

ios - Cocos2D - 最好保留 CGRect 数组或 CCSprite 数组来跟踪命中区域?

iOS 8.3 及更高版本,未插入 Facebook 分享文本

iphone - 在 UIToolBar 中垂直移动 UIBarButtonItems