[英]Move UIToolbar above keyboard when undocked
我有一个UIToolbar
位于屏幕底部。 当用户点击工具栏上的UITextField
时,将出现键盘,并且我会检测键盘的大小并通过更改其自动布局约束常量来向上移动工具栏。 (它具有对其下视图的底部间距限制。)这一直很好,直到用户取消(或拆分)iPad上的键盘为止。 那时工具栏的位置不正确。 我在“消息”应用程序中注意到,即使用户松开键盘,工具栏也始终位于键盘上方,并且在用户重新放置键盘时,它始终完全位于键盘上方。 经过研究后, 建议通过侦听UIKeyboardWillChangeFrameNotification
并检查UIKeyboardFrameEndUserInfoKey
来UIKeyboardFrameEndUserInfoKey
。 但是,该值可能不存在,因此我不确定在这种情况下该怎么做。
我的问题是,侦听键盘框架更改通知并更新自动布局约束的正确方法,还是要采取其他方法(弹出文本字段的inputAccessoryView
)? 如果是这样,如何检测和处理各种情况(隐藏,出现,更新框架,对接,重新定位),以确保始终将其始终恰好位于键盘上方,或者如果没有键盘(或其中有硬件键盘),则始终位于底部采用)?
请参阅下面的内容,以了解我当前如何处理UIKeyboardWillChangeFrameNotification
处理程序(Obj-C +伪代码的混合)中的键盘外观/外观/帧更改。
这样做的问题是,在取消对接/拆分时,工具栏的位置不正确,在取消对接时重新定位,并且使用了硬件键盘。 我还发现,在键盘未固定时展开/折叠QuickType不会触发UIKeyboardWillChangeFrameNotification
(在固定时会触发)。
keyboardFrameWillChange {
CGSize keyboardBeginSize = [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGSize keyboardEndSize = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
CGFloat newOffset = 0;
CGFloat toolbarPositionOffset = self.toolbarBottomConstraint.constant;
//get collection view's contentInset and contentOffset
//keyboard is appearing or disappearing or device is rotating with keyboard up
if keyboardEndSize.height == keyboardBeginSize.height {
if toolbarPositionOffset > 0 { //if dismissing
newOffset = keyboardEndSize.height;
toolbarPositionOffset -= newOffset;
//update content inset and offset
} else { //else appearing
newOffset = keyboardEndSize += newOffset;
toolbarPositionOffset += newOffset;
//update content inset and offset
}
}
//keyboard height increasing (expanding QuickType)
else if keyboardEndSize.height > keyboardBeginSize.height {
newOffset = keyboardEndSize.height - keyboardBeginSize.height;
toolbarPositionOffset += newOffset;
//update content inset and offset
}
//else keyboard height decreasing (collapsing QuickType)
else {
newOffset = keyboardBeginSize.height - keyboardEndSize.height;
toolbarPositionOffset -= newOffset;
//update content inset and offset
}
self.toolbarBottomConstraint.constant = toolbarPositionOffset;
//set new contentInset and offset
[self.toolbar layoutIfNeeded];
}
我没有找到可以解决我遇到的问题的解决方案,尽管它没有提供我想要的确切最终结果。 具体来说,您可以在这种情况下将工具栏固定在底部,而不是尝试在卸下/拆分时将工具栏移至键盘上方,并且仅将其固定在键盘上方时才将其放置在键盘上方。 这也解决了我在硬件键盘上遇到的问题。
侦听UIKeyboardWillShowNotification
并将工具栏的约束常量设置为等于UIKeyboardFrameEndUserInfoKey
值。
听UIKeyboardWillHideNotification
并将工具栏的约束常量设置为等于0
。
不要听UIKeyboardWillChangeFrameNotification
或任何其他键盘通知。
这样,这些通知将在键盘出现或隐藏时按您的期望发送。 但神奇的是(我可能不会很明显地添加),当键盘的框架发生变化(用户展开/折叠QuickType)时,将调用UIKeyboardWillShowNotification
。 而当用户太空站键盘, UIKeyboardWillShowNotification
被触发,则UIKeyboardWillHideNotification
之后立即触发。
这已在iOS 8.4上进行了测试,我可以想象这可能会因OS版本而异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.