ios - 如何在多个 View 上处理keyboardDidShow?

标签 ios xcode nsnotificationcenter

我有一个应用程序,通过让用户点击一个编辑按钮,在表格底部显示一个文本字段单元格,将新项目添加到表格 View 中,类似于内置的通知应用程序。当显示键盘时,我需要调整表格,以便当表格中有很多行时键盘不会受到阻碍。我通过订阅键盘显示时的通知来执行此操作:

- (void)viewDidLoad
{
    [super viewDidLoad];

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

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector (keyboardDidHide:)
                                                 name: UIKeyboardDidHideNotification
                                               object:nil];
}

...
...

-(void) keyboardDidShow: (NSNotification *)notif 
{
    // If keyboard is visible, return
    if (self.keyboardVisible) 
    {
        return;
    }

    // Get the size of the keyboard.
    NSDictionary* info = [notif userInfo];
    NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;

    // Adjust the table view by the keyboards height.
    self.tableView.contentInset =  UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);
    NSIndexPath *path = [NSIndexPath indexPathForRow:self.newsFeeds.count inSection:0];
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
    self.keyboardVisible = YES;
}

但是,我让用户添加行的表也可以被点击,并将新 View 推送到应用程序。该 View 还有一个 TextView ,当用户点击它并且键盘显示时,第一个 View Controller 仍然会收到通知,这会导致崩溃。

如何忽略通知或使其在推送新 View 时不触发?

最佳答案

您可以在 viewDidAppear 中将该类添加为观察者,并在 viewWillDisappear 中将其删除。

关于ios - 如何在多个 View 上处理keyboardDidShow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443292/

相关文章:

objective-c - exc_breakpoint 在调试中是什么意思?

ios - 嵌入在根框架中的签名子框架不起作用(Xcode 11.2.1)

ios - 我是否应该删除 NSUbiquitousKeyValueStoreDidChangeExternallyNotification 的通知

ios - 谷歌登录 CocoaPods 在 Swift 中安装?

基于 Firebase 数据库的 ios 应用程序 - 在本地合并更改

xcode - 如何使用 Xcode 工具栏中的菜单进行分段控制

ios - 如何使用通知更改 uitableviewcell 自定义 uilabel 而无需在 ios swift 中重新加载整个表数据

ios - 使用 AFNetworking 的共享扩展未获得成功/失败回调

ios - 如何在 Swift 项目中集成 PjSip?

ios - 触发 tintColorDidChange 以响应用户操作使有色元素去饱和