![](/img/trans.png)
[英]How can I hide the keyboard in the UI in Swift Playgrounds (on Xcode) that appears in the Live View when I create a UITextView?
[英]How can I keep UITableView in view when keyboard appears?
我正在尝试在标准样式消息屏幕的应用程序中创建一个页面。 当键盘滑入视图时,我无法使所有位置正确定位。 我将发布屏幕截图(严重地不是内联),但这是我的结构:
VIEWCONTROLLER
|-View
|-Scroll View
|-Content View
|-TextField
|-TableView (messages)
一切都显示为我第一次加载时想要的样子:如果没有足够的消息填充屏幕,则消息从顶部开始,后跟一个空格,文本字段固定在底部。 没有滚动。 如果有很多消息,我可以成功地将表格滚动到最后一行,并将文本字段固定在屏幕底部。
但是,当文本字段被激活并且没有很多消息时,表和文本字段之间的间隙仍然存在,并且消息被推到顶部。
我正在努力缩小差距,以便保留消息。 这在其他消息传递应用程序中是标准的,但我不知道该怎么做
最后,这是我拥有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不够了解。 谢谢您的帮助!
编辑:问题类似于此问题 ,没有可接受的答案。
一种方法是设置像这样的垂直自动布局约束(但是您需要引用实际的bottomMargin
约束才能进行修改):
"V:|[scrollView][textField]-(bottomMargin)-|"
第一次到达屏幕时, bottomMargin
设置为0
。
然后在调用keyboardWillShow
时,获取键盘框架(参见如何获取键盘的高度? )
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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.