首页 > 解决方案 > 从屏幕底部到卡片视图内部的视图高度?(打开时在键盘上方移动视图)

问题描述

我有一个相当复杂的情况。它与在键盘上方移动视图有关。我有一个聊天视图,很像 Apple 的消息应用程序。但是,它位于不填满整个屏幕的卡片内部。该卡片的上方和下方是导航栏和标签栏。

现在,当他们点击键盘时,我想将可编辑的 UITextView(用户撰写消息的地方)移到键盘上方。我确实有键盘的高度(使用 NotificationCenter Observer),但我需要从键盘的高度中减去 textview 的高度(卡片内部),以计算我应该偏移 textview 的距离。图片可能会有所帮助:

这是我的视图堆栈:视图 -> 卡片视图 -> 滚动视图(包含消息列表表视图和聊天表视图)-> 文本框视图(包含 UITextView、发送按钮等)

这是可行的吗?有没有更好的方法来做到这一点?我被困住了,并且在操纵有关键盘的视图方面还很陌生。

这是我到目前为止的代码片段:

    fileprivate var keyboardHeight = CGFloat()
    
    @objc fileprivate func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
            self.keyboardHeight = keyboardHeight
        }
    }
    
    fileprivate func moveTextView(textView: UITextView, moveDistance: Int, up: Bool) {
        let moveDuration = 0.3
        let movement = CGFloat(up ? moveDistance : -moveDistance)
        
        UIView.animate(withDuration: moveDuration) {
            self.snp.updateConstraints({ (make) in
                make.bottom.equalToSuperview().offset(movement)
            })
            
            self.superview?.layoutIfNeeded()
        }
        
    }

extension TextBarView: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        moveTextView(textView: textView, moveDistance: -200, up: true)
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        moveTextView(textView: textView, moveDistance: -200, up: false)
    }
    
    func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        textView.resignFirstResponder()
        return true
    }
}

我正在使用 SnapKit 进行自动布局。

(如果你看完了整篇文章,谢谢!)

标签: iosswiftuiviewkeyboardsnapkit

解决方案


推荐阅读