You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击消息Collection View时如何收起键盘?

点击MessageKit消息CollectionView收起键盘的问题与解决方法

我尝试通过给messagesCollectionView添加点击手势实现收起键盘,代码如下:

let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapBackground))
self.messagesCollectionView.addGestureRecognizer(tap)

@objc private func didTapBackground() {
    print("tapped")
    messageInputBar.inputTextView.resignFirstResponder()
}


private func configureMessageInputBar() {
    messageInputBar.delegate = self
    
    let button = InputBarButtonItem()
    button.image = UIImage(named: "attach")
    button.setSize(CGSize(width: 36, height: 36), animated: false)
    
    button.onTouchUpInside { (item) in
        self.actionAttachMessage()
    }
    
    messageInputBar.setStackViewItems([button], forStack: .left, animated: false)
    messageInputBar.setLeftStackViewWidthConstant(to: 36, animated: false)

    messageInputBar.contentView.backgroundColor = .clear
    messageInputBar.inputTextView.layer.borderColor = #colorLiteral(red: 0.5568627451, green: 0.4705882353, blue: 0.9568627451, alpha: 1)
    messageInputBar.inputTextView.layer.borderWidth = 3
    messageInputBar.inputTextView.layer.cornerRadius = 16
    messageInputBar.inputTextView.isImagePasteEnabled = false
 
    messageInputBar.inputTextView.backgroundColor = .clear
    messageInputBar.isTranslucent = true
   
    messageInputBar.inputTextView.textColor = .white
}

使用框架:MessageKit

问题截图:
问题截图


解决方案

方法一:利用MessageKit内置方法

如果你的控制器继承自MessagesViewController,框架已经内置了交互处理逻辑,直接重写点击方法即可:

override func didTapMessageCollectionView(at indexPath: IndexPath) {
    super.didTapMessageCollectionView(at: indexPath)
    messageInputBar.inputTextView.resignFirstResponder()
}

方法二:修复自定义手势冲突

若坚持使用自定义手势,需解决与CollectionView原生手势的冲突:

  1. 修改手势属性,允许同时触发原生手势:
let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapBackground))
tap.cancelsTouchesInView = false // 关键设置
self.messagesCollectionView.addGestureRecognizer(tap)
  1. (可选)通过手势代理允许同时识别:
tap.delegate = self

// 遵循UIGestureRecognizerDelegate协议
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

这样既不影响消息单元格的点击交互,也能触发收起键盘的逻辑。


内容的提问来源于stack exchange,提问作者Dani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:27:59