ios - 在键盘上方显示 UIView 无法正常工作

标签 ios swift uiview nslayoutconstraint nsnotificationcenter

我正在尝试移动 UIViewconstraintToBottom.constant,其中显示后我的 UITextField 位于键盘上方。我设置了 Notification 观察器,但由于某种原因它不起作用。

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        UIView.animate(withDuration: 0.3, animations: {
            self.constraintToBottom.constant = keyboardSize.height
            print("constant", self.constraintToBottom.constant)
        })
    }
}

当我打印 constraintToBottom.constant 时,它显示:

constant 346.0

然而,UIView 仍然像往常一样在键盘上方不可见。我做错了什么?

更新

如建议的那样,减号可以解决问题,但还有额外的空间,看起来像这样:

enter image description here

最佳答案

需要重新布局 View

self.constraintToBottom.constant = -1 * keyboardSize.height
UIView.animate(withDuration: 0.3, animations: {
     self.view.layoutIfNeeded()
     print("constant", self.constraintToBottom.constant)
})

关于ios - 在键盘上方显示 UIView 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52692446/

相关文章:

IOS Swift Segue 使用来自选定单元格而不是支持数组的数据

swift - 如何在 Swift 中创建一个递增值的数组?

ios - 如何在 UILabel 的文本下绘制内容?

ios - 如何将 UIView 旋转 45 度?

ios - 我不知道使用 UIView.animate 或创建 UIImageView 方法有什么问题。我使用快速语言

ios - 定义模态视图尺寸 ?

ios - 为什么在尝试删除 TableView ios 中的部分时出现断言错误

ios - 使用无法访问的 View Controller 作为标签是不好的做法吗?

swift - 单击菜单按钮时如何激活菜单栏 (NSPopover) 应用程序?

ios - 如何停止 MPMediaPickerController 使用重复的 MPMediaItems 填充 MPMediaItemCollection?