gpt4 book ai didi

Ios消息应用程序,如何控制键盘

转载 作者:行者123 更新时间:2023-11-30 13:36:16 25 4
gpt4 key购买 nike

我已经在即时通讯应用程序上开发了。当用户点击文本字段时,键盘会弹出,包含消息的表格 View 会向上移动,但表格 View 的顶部不可见,因为它不在屏幕上。当用户向上或向下移动键盘建议时,它还会产生使屏幕变黑的不良效果

override func viewWillAppear(animated:Bool) {
super.viewWillAppear(animated)

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}



func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
kbHeight = keyboardSize.height
self.animateTextField(true)
}
}
}

func keyboardWillHide(notification: NSNotification) {
self.animateTextField(false)
}

func animateTextField(up: Bool) {
let movement = (up ? -kbHeight : kbHeight)

UIView.animateWithDuration(0.2, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
})
}

如何控制表格 View 、文本字段和键盘的显示?

编辑

期望的行为。从一开始

  • 我希望折叠 View 键盘(工作正常)
  • 显示消息的表格 View (工作正常)
  • 屏幕底部的文本字段(工作正常)

当点击文本字段时

  • 键盘弹出(工作)
  • 文本字段移至键盘顶部(工作)
  • 表格 View 显示在文本字段上方的剩余空间中(不起作用,它位于文本字段上方,但一半屏幕溢出到顶部)

其他错误

  • 显示/隐藏键盘顶部的自动完成单词时屏幕变黑

最佳答案

我找到了解决方案,它对我有用。

请检查您的项目。 (Eendje 的解决方案)

Resize the screen when keyboard appears

您可以创建表格 View 底部自动布局约束的导出。

然后只需使用此代码:

func keyboardWillShow(sender: NSNotification) {
let info = sender.userInfo!
var keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height
bottomConstraint.constant = keyboardSize - bottomLayoutGuide.length

let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue

UIView.animateWithDuration(duration) { self.view.layoutIfNeeded() }
}

func keyboardWillHide(sender: NSNotification) {
let info = sender.userInfo!
let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
bottomConstraint.constant = 0

UIView.animateWithDuration(duration) { self.view.layoutIfNeeded() }
}

如果您在创建底部约束时遇到困难:

在 Storyboard中

选择您的搜索栏。在右下角,您会看到 3 个图标。单击中间的一个,看起来像 |-[]-|。在该弹出窗口的顶部,有 4 个框。在底部的 1 处输入 0。约束已创建!现在您可以将其拖动到 View Controller 并将其添加为 socket 。

另一个解决方案是设置tableView.contentInset.bottom。但我以前没有这样做过。如果您愿意,我可以尝试解释一下。

使用插图:

func keyboardWillShow(sender: NSNotification) {
let info = sender.userInfo!
var keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height

tableView.contentInset.bottom = keyboardSize
}

func keyboardWillHide(sender: NSNotification) {
tableView.contentInset.bottom = 0
}

您可以尝试使用此代码来设置插图。我自己还没试过,但应该是这样的。

我使用约束解决方案来解决我的问题。

关于Ios消息应用程序,如何控制键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36038573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com