如何在多个视图中处理键盘DidShow



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

- (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;
}

然而,我让用户添加行的表也可以点击,并将新视图推送到应用程序上。这个视图还有一个文本视图,当用户点击它并且键盘显示第一个视图控制器时,它仍然会收到通知,这会导致崩溃。

当推送新视图时,我如何忽略通知或使其不启动?

您可以在viewDidPear中添加该类作为观察者,并在viewWillDisappear中删除它。

最新更新