简体   繁体   中英

How to pin a UIView to the bottom of its superview, but have it move when the keyboard appears?

I have a UIView with a UIView and UITableView in it. The child UIView is for composition, it has textfield and a Send button like any messenger. How can I pin/fix this child UIView to the bottom of the Superview and keep it visibly on top of the UITableView? However the child UIView needs to also rise above the keyboard when its textfield is focused.

You can do this manually. You can sign up for getting keyboard notifications. You can the following functions

    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];

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

There is a very good article about this on Apple Keyboard Management with code snippets.

The answer to your question is different for AutoLayout and for AutoResizingMasks (struts and springs) style layout.

For AutoLayout, the default for Xcode 6, what you would do would be to create a constraint to pin your view to the bottom of it's superview, as normal. Then you'd select that constraint in IB and control-drag it into the header file of your view controller, and create an IBOutlet for the constraint.

You can then write a notification handler for the keyboard will show notification, and in that handler, change the constant (offset) of your constraint property. The final step is to put a call to your superview's layoutIfNeeded method inside a UIView animation block. That causes the layout change from updating the constraint to be animated.

You then do the opposite for a keyboard will hide notification.

If you're doing struts-and-springs style layout, it's similar but simpler. You just create an outlet to the view that you want to move, and then make your keyboard will show notification handler use a UIView animation to animate a change to the view's center property .

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