简体   繁体   中英

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

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?

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.

eg 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM