效果
声明:原作者为 TSWeChat,这里只是记录笔者移植到自己项目中使用的过程。
安装
pod添加依赖:
pod 'Dollar', '9.0.0' # 操作数组的神器,比如将数组划分成若干个子集
pod 'RxSwift', '~> 5' # 一个组合异步和事件驱动编程的库
pod 'RxCocoa', '~> 5' # iOS响应式编程中的两个主流框架(RxSwift+RxCocoa)
pod 'SnapKit', '~> 5.0.0' # 自动布局第三方库
代码实例
工具类
- UIImage+Chat.swift,图片资源
import Foundation
import UIKit
typealias IMAssets = UIImage.Asset
// 资源文件的快速访问
extension UIImage {
enum Asset: String {
case Chat_add_friend = "chat_add_friend"
case Chat_add_newmessage = "chat_add_newmessage"
case Chat_add_scan = "chat_add_scan"
case Chat_MessageRightTopBg = "chat_MessageRightTopBg"
case Chat_add = "chat_add"
// 还可以这样写?
var image: UIImage {
return UIImage(asset: self)
}
}
// 便利构造函数通常都是写在extension里面
convenience init!(asset: Asset) {
self.init(named: asset.rawValue)
}
}
- UINavigationItem+Extension.swift
import Foundation
import UIKit
//
// 来自于[TSWeChat](https://github.com/hilen/TSWeChat)
//
public typealias ActionHandler = () -> Void
public extension UINavigationItem {
// left bar
func leftButtonAction(_ image: UIImage, action: @escaping ActionHandler) {
let button: UIButton = UIButton(type: UIButton.ButtonType.custom)
button.setImage(image, for: UIControl.State())
button.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
button.imageView!.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .left
button.ngl_addAction(forControlEvents: .touchUpInside, withCallback: {
action()
})
let barButton = UIBarButtonItem(customView: button)
let gapItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
gapItem.width = -7 // fix the space
self.leftBarButtonItems = [gapItem, barButton]
}
// right bar
func rightButtonAction(_ image: UIImage, action: @escaping ActionHandler) {
let button: UIButton = UIButton(type: UIButton.ButtonType.custom)
button.setImage(image, for: UIControl.State())
button.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
button.imageView!.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .right
button.ngl_addAction(forControlEvents: .touchUpInside, withCallback: {
action()
})
let barButton = UIBarButtonItem(customView: button)
let gapItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
gapItem.width = -7 // fix the space
self.rightBarButtonItems = [gapItem, barButton]
}
}
/*
Block of UIControl
*/
open class ClosureWrapper : NSObject {
let _callback : () -> Void
init(callback : @escaping () -> Void) {
_callback = callback
}
@objc open func invoke() {
_callback()
}
}
var AssociatedClosure: UInt8 = 0
extension UIControl {
fileprivate func ngl_addAction(forControlEvents events: UIControl.Event, withCallback callback: @escaping () -> Void) {
let wrapper = ClosureWrapper(callback: callback)
addTarget(wrapper, action:#selector(ClosureWrapper.invoke), for: events)
objc_setAssociatedObject(self, &AssociatedClosure, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
- IMActionFloatView.swift
import Foundation
import UIKit
import SnapKit
import Dollar
import RxSwift
import RxCocoa
private let kActionViewWidth: CGFloat = 140 //container view width
private let kActionViewHeight: CGFloat = 155 //container view height
private let kActionButtonHeight: CGFloat = 44 //button height
private let kFirstButtonY: CGFloat = 12 //the first button Y value
class IMActionFloatView: UIView {
weak var delegate: ActionFloatViewDelegate?
let disposeBag = DisposeBag()
override init (frame: CGRect) {
super.init(frame : frame)
self.initContent()
}
convenience init () {
self.init(frame:CGRect.zero)
self.initContent()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate func initContent() {
self.backgroundColor = UIColor.clear
let actionImages = [
IMAssets.Chat_add_friend.image,
IMAssets.Chat_add_newmessage.image,
IMAssets.Chat_add_scan.image,
]
let actionTitles = [
"发起群聊",
"添加朋友",
"扫一扫",
]
//Init containerView
let containerView : UIView = UIView()
containerView.backgroundColor = UIColor.clear
self.addSubview(containerView)
containerView.snp.makeConstraints { (make) -> Void in
make.top.equalTo(self.snp.top).offset(3)
make.right.equalTo(self.snp.right).offset(-5)
make.width.equalTo(kActionViewWidth)
make.height.equalTo(kActionViewHeight)
}
//Init bgImageView
let stretchInsets = UIEdgeInsets.init(top: 14, left: 6, bottom: 6, right: 34)
let bubbleMaskImage = IMAssets.Chat_MessageRightTopBg.image.resizableImage(withCapInsets: stretchInsets, resizingMode: .stretch)
let bgImageView: UIImageView = UIImageView(image: bubbleMaskImage)
containerView.addSubview(bgImageView)
bgImageView.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(containerView)
}
//init custom buttons
var yValue = kFirstButtonY
for index in 0 ..< actionImages.count {
let itemButton: UIButton = UIButton(type: .custom)
itemButton.backgroundColor = UIColor.clear
itemButton.titleLabel!.font = UIFont.systemFont(ofSize: 17)
itemButton.setTitleColor(UIColor.white, for: UIControl.State())
itemButton.setTitleColor(UIColor.white, for: .highlighted)
// title
let title = Dollar.fetch(actionTitles, index, orElse: "")
itemButton.setTitle(title, for: .normal)
itemButton.setTitle(title, for: .highlighted)
// header image
let image = Dollar.fetch(actionImages, index, orElse: nil)
itemButton.setImage(image, for: .normal)
itemButton.setImage(image, for: .highlighted)
itemButton.addTarget(self, action: #selector(IMActionFloatView.buttonTaped(_:)), for: UIControl.Event.touchUpInside)
itemButton.contentHorizontalAlignment = .left
itemButton.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 12, bottom: 0, right: 0)
itemButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
itemButton.tag = index
// parent view
containerView.addSubview(itemButton)
itemButton.snp.makeConstraints { (make) -> Void in
make.top.equalTo(containerView.snp.top).offset(yValue)
make.right.equalTo(containerView.snp.right)
make.width.equalTo(containerView.snp.width)
make.height.equalTo(kActionButtonHeight)
}
yValue += kActionButtonHeight
}
//add tap to view
let tap = UITapGestureRecognizer()
self.addGestureRecognizer(tap)
tap.rx.event.subscribe { _ in
self.hide(true)
}.disposed(by:self.disposeBag)
self.isHidden = true
}
@objc func buttonTaped(_ sender: UIButton!) {
guard let delegate = self.delegate else {
self.hide(true)
return
}
let type = ActionFloatViewItemType(rawValue:sender.tag)!
delegate.floatViewTapItemIndex(type)
self.hide(true)
}
/**
Hide the float view
- parameter hide: is hide
*/
func hide(_ hide: Bool) {
if hide {
self.alpha = 1.0
UIView.animate(withDuration: 0.2 ,
animations: {
self.alpha = 0.0
},
completion: { finish in
self.isHidden = true
self.alpha = 1.0
})
} else {
self.alpha = 1.0
self.isHidden = false
}
}
}
/**
* TSMessageViewController Float view delegate methods
*/
protocol ActionFloatViewDelegate: class {
/**
Tap the item with index
*/
func floatViewTapItemIndex(_ type: ActionFloatViewItemType)
}
enum ActionFloatViewItemType: Int {
case groupChat = 0, addFriend, scan, payment
}
使用
- 在任意ViewController.swift中,声明一个变量
class IMChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, IMConversationManagerDelegate {
@IBOutlet var sessionTabView: UITableView!
var list: [SessionModel] = []
// 声明
var actionFloat: IMActionFloatView!
}
2.在viewDidLoad初始化悬浮框
override func viewDidLoad() {
super.viewDidLoad()
// 在顶部右侧添加按钮(加群、扫一扫、加朋友等)
self.navigationItem.rightButtonAction(IMAssets.Chat_add.image) { () -> Void in
self.actionFloat.hide(!self.actionFloat.isHidden)
}
//Init ActionFloatView
self.actionFloat = IMActionFloatView()
self.actionFloat.delegate = self
self.view.addSubview(self.actionFloat)
self.actionFloat.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(UIEdgeInsets.init(top: 85, left: 0, bottom: 0, right: 0))
}
// ……
}
3.监听点击回调
// MARK: - @protocol ActionFloatViewDelegate
extension IMChatViewController: ActionFloatViewDelegate {
func floatViewTapItemIndex(_ type: ActionFloatViewItemType) {
IMLog.info(item: "floatViewTapItemIndex:\(type)")
switch type {
case .groupChat:
break
case .addFriend:
break
case .scan:
break
case .payment:
break
}
}
}
关于作者
推荐下自己的开源IM,纯Golang编写:
CoffeeChat:
https://github.com/xmcy0011/CoffeeChat
opensource im with server(go) and client(flutter+swift)
参考了TeamTalk、瓜子IM等知名项目,包含服务端(go)和客户端(flutter+swift),单聊和机器人(小微、图灵、思知)聊天功能已完成,目前正在研发群聊功能,欢迎对golang和跨平台开发flutter技术感兴趣的小伙伴Star加关注。
————————————————
版权声明:本文为CSDN博主「许非」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xmcy001122/article/details/109381059