我正在尝试在应用程序中创建一个标准样式消息传递屏幕的页面。当键盘滑入视图时,我无法正确定位所有内容。我会发布截图(遗憾的是不是内联),但这是我的结构:
VIEWCONTROLLER
|-View
|-Scroll View
|-Content View
|-TextField
|-TableView (messages)
首次加载时,所有内容都显示为我想要的内容:如果没有足够的消息填充屏幕,则消息从顶部开始,后跟间隙,文本字段固定在底部。什么都不滚动。如果有很多消息,我成功地将表格滚动到最后一行,文本字段仍然固定在屏幕的底部。
但是,当文本字段被激活时,并且没有很多消息,表格和文本字段之间的差距仍然存在,消息被推出视图顶部。
我正在努力缩小差距,以便留言。这是其他消息传递应用程序的标准,但我无法弄清楚如何做到这一点
Textfield activated, keyboard appears
Scrolling to display messages hides the textfield
最后,这是我keyboardWillShow
的代码。你会注意到我尝试过的一些事情没有成功。
func keyboardWillShow(notification:NSNotification) {
var userInfo = notification.userInfo!
let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardFrame!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
// scrollViewBottomConstraint.constant = keyboardFrame!.height - bottomLayoutGuide.length
// contentViewHeightConstraint.constant = -keyboardFrame!.height
// self.notificationReplyTable.frame.size.height -= keyboardFrame!.height
var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardFrame!.height
if let activeField = self.activeField {
if(!aRect.contains(activeField.frame.origin)) {
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
}
我觉得我失踪的那件作品非常小,但只是不知道Swift 3能够指出这一点。谢谢你的帮助!
编辑:问题类似于this question,没有接受的答案。
答案 0 :(得分:0)
一种方法是设置这样的垂直自动布局约束(但您需要引用实际的bottomMargin
约束才能修改它):
"V:|[scrollView][textField]-(bottomMargin)-|"
第一次到达屏幕时,bottomMargin
设置为0
。
然后在调用keyboardWillShow
时,获取键盘框架(cf How to get height of Keyboard?)
func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
设置约束bottomMargin
的动画以获得键盘的高度(某些测试后持续时间为0.3,但您可以调整它):
bottomConstraint.constant = keyboardHeight
UIView.animate(withDuration: 0.3, delay: 0, options: nil, animations: {
self.view.layoutIfNeeded()
}
这意味着每次键盘出现时,动画都会向上移动文本字段,因此滚动视图高度会更小,所有内容都适合屏幕。
!!不要忘记在横向模式下测试它,如果你支持它,也可以在iPad上测试!!
最后,当键盘在keyboardWillHide
中消失并将bottomMargin
设置回0时处理案例:
func keyboardWillHide(_ notification: Notification) {
bottomConstraint.constant = 0
UIView.animate(withDuration: 0.3, delay: 0, options: nil, animations: {
self.view.layoutIfNeeded()
}
}