简体   繁体   English

如何将UIView固定到其超级视图的底部,但是当出现键盘时将其移动?

[英]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. 我有一个带有UIView和UITableView的UIView。 The child UIView is for composition, it has textfield and a Send button like any messenger. 子UIView用于合成,它具有文本字段和类似于任何Messenger的Send按钮。 How can I pin/fix this child UIView to the bottom of the Superview and keep it visibly on top of the UITableView? 如何将该子UIView固定/固定在Superview的底部,并使其可见地位于UITableView的顶部? However the child UIView needs to also rise above the keyboard when its textfield is focused. 但是,当子UIView的文本字段处于焦点位置时,它也需要提升到键盘上方。

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. 关于Apple Keyboard Management,有一篇很好的文章,带有代码片段。

The answer to your question is different for AutoLayout and for AutoResizingMasks (struts and springs) style layout. 您的问题的答案对于AutoLayout和AutoResizingMasks(支柱和弹簧)样式布局是不同的。

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. 对于AutoLayout,这是Xcode 6的默认设置,您将执行的操作是创建一个约束,以正常方式将视图固定在其超级视图的底部。 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. 然后,您将在IB中选择该约束并将其控制拖放到视图控制器的头文件中,并为该约束创建IBOutlet。

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. 然后,您可以编写一个通知处理程序,使keyboard will show通知,并在该处理程序中更改约束属性的常数(偏移)。 The final step is to put a call to your superview's layoutIfNeeded method inside a UIView animation block. 最后一步是在UIView动画块内调用父视图的layoutIfNeeded方法。 That causes the layout change from updating the constraint to be animated. 这会导致布局更改从更新约束变为动画。

You then do the opposite for a keyboard will hide notification. 然后您执行相反操作, keyboard will hide通知。

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 . 您只需为要移动的视图创建一个出口,然后使keyboard will show通知处理程序,并使用UIView动画为视图的center属性设置动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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