你如何在多个视图上处理keyboardDidShow?

时间:2012-09-15 23:41:24

标签: ios xcode nsnotificationcenter

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

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

但是,我也可以点击我允许用户添加行的表格,并将新视图推送到应用程序。此视图还有一个文本视图,当用户点击它并且键盘显示第一个viewcontroller仍然会收到通知,这会导致崩溃。

如何在推送新视图时忽略通知或不触发通知?

1 个答案:

答案 0 :(得分:1)

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