Swift- 调整约束以允许键盘

Swift- Adjusting Constraints to allow for keyboard

我是一名新 SWIFT 程序员,学习编码是一种爱好。我即将完成我的第一个应用程序并有一个表格视图,其中单元格的一部分包含一个文本字段,用户可以在其中编辑其中包含的数据。

当用户在文本字段中单击时,键盘会弹出并遮住大部分表格视图。

我已经对此进行了研究,并且在过去的一个小时里一直在研究解决方案领域,但我有点不知从何入手。据我所知,我应该只调整 tableview 的约束,使其从视图底部开始不是 0,而是键盘的高度是多少像素。

所以我理解了这个概念,但不知道如何执行这两个主要部分:

  1. 如何设置侦听器以便在键盘出现时我可以运行一些代码
  2. 如何以编程方式设置 tableview 的约束?

您需要在 viewDidLoad 中附加一些观察者:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: UIResponder.keyboardWillHideNotification, object: nil)

记得在 viewWillDisappear 中删除它们:

NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)

您需要一个@objc 函数供您的观察者调用:

@objc private func keyboardWillChange(_ notification: Notification) {
        guard let userInfo = (notification as Notification).userInfo, let value = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
            return
        }
    
    if ((userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
        var newHeight: CGFloat
        let textHeight = inputTextView.textContainer.size.height
        
        if isKeyboardShowing {
            newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
            bottomConstraint.constant = newHeight + textHeight
            view.bringSubviewToFront(messageInputContainerView)
            UIView.animate(withDuration: 0, delay: 0,
                               options: .curveEaseOut,
                               animations: { self.view.layoutIfNeeded() },
                               completion: nil)
        }
        else {
            view.bringSubviewToFront(messageInputContainerView) 
            newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
            bottomConstraint?.constant = view.safeAreaInsets.bottom + messageInputContainerView.bounds.height - textHeight
            UIView.animate(withDuration: 0,
                           delay: 0,
                           options: .curveEaseOut,
                           animations: { self.view.layoutIfNeeded() },
                           completion: nil)
        }
    }
}

bottomConstraint 是您的 class 引用,在这种情况下附加到故事板上 tableView 的底部,并且是我们在键盘打开和关闭时的可移动基线。您将需要调整值和约束选项以供您自己使用 case/sizes。 messageInputContainerView 是本例中 inputTextView 的容器。