如何为JSQMessage聊天气泡添加自定义菜单选项
为JSQMessagesViewController添加自定义长按菜单选项
嘿,我来帮你搞定这个需求!在JSQMessages里扩展长按菜单其实很简单,只需要在现有的UICollectionView菜单方法里补充自定义逻辑就行,我一步步给你讲:
1. 定义自定义选项的Selector和处理方法
首先,你需要声明自定义选项对应的动作方法(必须用@objc修饰,因为Objective-C运行时需要识别它),比如我们加一个「转发」选项:
// 自定义选项的标识字符串 private let quickChatOptionForward = "forward:" // 处理转发动作的方法 @objc func forwardMessage(_ sender: Any?) { // 后续在这里填充转发的具体逻辑 }
2. 修改canPerformAction方法,允许显示自定义选项
你已经写了判断删除权限的逻辑,现在把自定义选项和默认的「复制」选项都加进去,控制哪些选项可以显示:
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { let message = messageList[indexPath.item] switch action.description { case "copy:": // JSQ默认复制选项的标识是"copy:" return true // 可根据需求调整权限,比如仅允许复制自己的消息 case quickChatOptionDelete: // 保留你原来的删除权限逻辑:仅自己发送的消息可删除 return message.senderId == strMemberID case quickChatOptionForward: // 自定义转发选项 return true // 这里可添加权限判断,比如仅允许转发特定类型的消息 default: return false } }
3. 重写performAction方法,处理自定义选项的点击逻辑
这一步是核心,当用户点击菜单选项时,执行对应的操作:
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { let message = messageList[indexPath.item] switch action.description { case "copy:": // 可使用JSQ默认复制逻辑,或自定义实现 UIPasteboard.general.string = message.text case quickChatOptionDelete: // 执行删除逻辑,记得刷新UI messageList.remove(at: indexPath.item) collectionView.deleteItems(at: [indexPath]) // 调用JSQ的方法刷新聊天界面 self.finishReceivingMessage() case quickChatOptionForward: // 这里写你的转发逻辑,比如跳转到联系人选择页、弹出分享菜单等 print("准备转发消息:\(message.text ?? "")") // 举个简单示例:弹出提示框确认转发 let alert = UIAlertController(title: "转发消息", message: message.text, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "取消", style: .cancel)) alert.addAction(UIAlertAction(title: "确定转发", style: .default, handler: { _ in // 在这里编写实际的转发代码,比如调用接口发送给目标联系人 })) present(alert, animated: true) default: super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender) } }
额外注意点
- 如果需要添加更多自定义选项,只需要重复上述步骤:新增标识字符串、
@objc方法,然后在两个菜单方法里添加对应的case即可。 - 权限控制:如果某些消息不允许执行某个操作,只需在
canPerformAction的对应case里返回false。 - 界面刷新:处理完删除、转发等操作后,一定要调用JSQ的
finishReceivingMessage()或reloadData()更新聊天界面,避免出现UI异常。
内容的提问来源于stack exchange,提问作者aqsa arshad
相关产品推荐
相关产品推荐

