How can I prevent the keyboard from covering up subviews on a UIViewController?

331 views Asked by At

In my UITableViewControllers, when a keyboard is shown on screen, I typically animate up the bottom of the tableView via a NSLayoutConstraint IBOutlet such as @property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintTableViewBottomToSuperViewBottom. Then if the keyboard animates on screen, I add the size of the keyboard to the constraint, and if the keyboard disappears I remove the keyboards size from the constraint.

Works like a charm.

Now, I need to do the SAME thing but with a UIViewController as opposed to a UITableViewController.

I'm a bit confused tho. When I do this with a UITableViewController, it's easy. My tableView gets smaller in height with the keyboard showing, but I can still see all my data easily by scrolling the tableView up and down.

If I do this with a UIViewController's main UIView, when the keyboard is shown on screen I would shorten the height of the UIViewController's main View, but that will shrink/skew all the subviews on this main view, compacting them. How do you get around this?

1

There are 1 answers

3
Adama On

If you need to allow the user to drag around the view while the keyboard is Visible, then you'll need to do all of your layout inside of a ScrollView which will work just like your UITableView method.

If you just need to move up and show what is behind the keyboard, and don't need to allow the user the ability to drag the view, then you can just get the viewcontroller's main view (self.view) and reassign its frame.

e.g. self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - keyboardHeight, self.view.frame.size.width, self.view.frame.size.height);