Reputation: 20237
I have an app where I add a new item to a table view by having the user tap an edit button which shows a textfield cell at the bottom of the table, similar to the built in Notifications app. I need to adjust the table when the keyboard is shown so that it is not obstructed when their are many rows in the table. I am doing this by subscribing to the notification for when the keyboard shows:
- (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;
}
However, the table that I let a user add a row to can also be tapped and a new view is pushed on to the app. This view also has a text view and when the user taps in it and the keyboard shows the first viewcontroller still gets the notification, which causes a crash.
How can I either ignore the notification or get it to not fire when a new view is pushed?
Upvotes: 2
Views: 1841
Reputation: 3940
You could add the class as an observer in viewDidAppear and remove it in viewWillDisappear.
Upvotes: 2