繁体   English   中英

快速调整约束以允许使用键盘

[英]Swift- Adjusting Constraints to allow for keyboard

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

当用户在文本字段中单击时,键盘会弹出并遮挡大部分 tableview。

我已经对此进行了研究,并在最后一个小时内一直在研究解决方案的领域,但我对从哪里开始有点困惑。 尽我所知,我应该调整 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是您的类参考,它附加到故事板上的 tableView 的底部,并且是键盘打开和关闭时的可移动基线。 您需要为自己的用例/大小调整值和约束选择。 在这个例子中, messageInputContainerView是我们inputTextView的容器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM