iOS Quicktip: Adjusting View for Text Entry in a UITableView

Published Mar 24, 2015Last updated Apr 14, 2017

The Purpose of this Tutorial

Well, in iOS, when adding a custom table view cell to a UITableView with a UITextField in it, there won't be an automatic adjustment to move the table view so that while entering text, you always see what's going on. Instead, your text will be covered by the keyboard, and frustration will ensue!

This tutorial is to avoid that frustration!

So You have a Table View Controller

It's actually fairly simple to do this, it's just not known to many...You need to get notified of keyboard notifications through the NSNotificationCenter. This is done as follows:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

This code lives in the viewDidLoad method, and notifies this view controller of the notifications we want to be aware of, and redirects those notifications to keyboardWillShow method and keyboardWillHide method.

keyboardWillShow:

- (void)keyboardWillShow:(NSNotification *)notification
   {
       CGSize keyboardSize = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
       NSNumber *rate = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
 
       UIEdgeInsets contentInsets;
       if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
            contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.height), 0.0);
    } else {
        contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.width), 0.0);
        }
 
    [UIView animateWithDuration:rate.floatValue animations:^{
     self.myTableView.contentInset = contentInsets;
     self.myTableView.scrollIndicatorInsets = contentInsets;
     }];
    [self.myTableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }

keyboardWillHide:

- (void)keyboardWillHide:(NSNotification *)notification
{
    NSNumber *rate = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
    [UIView animateWithDuration:rate.floatValue animations:^{
    	self.myTableView.contentInset = UIEdgeInsetsZero;
    	self.myTableView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }];
}

What Else Do I Need?

Well you need to make sure that the notification observation ends when this view controller goes out of scope, so we have to implement dealloc.

dealloc

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

And that's it!

You've successfully moved the cursor to right above the keyboard!

Discover and read more posts from Benjamin Hendricks
get started
Enjoy this post?

Leave a like and comment for Benjamin