Swift-WeChatを模倣して、グループチャットフローティングフレームの実装を開始します

効果

ここに画像の説明を挿入

免責事項:元の作者はTSWeChatです。ここでは、作者を自分のプロジェクトに移植するプロセスを記録しています。

インストール

ポッド追加の依存関係:

pod 'Dollar', '9.0.0'      # 操作数组的神器,比如将数组划分成若干个子集
pod 'RxSwift', '~> 5'      # 一个组合异步和事件驱动编程的库
pod 'RxCocoa', '~> 5'      # iOS响应式编程中的两个主流框架(RxSwift+RxCocoa)
pod 'SnapKit', '~> 5.0.0'  # 自动布局第三方库

コード例

ツール

  1. 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)
    }
}
  1. 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)
    }
}
  1. 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
}

使用する

  1. 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
        }
    }
}

著者について

純粋なGolangで書かれた独自のオープンソースIMをお勧めします。

CoffeeChat:
https //github.com/xmcy0011/CoffeeChat
オープンソースim with server(go)and client(flutter + swift)

サーバー(go)とクライアント(flutter + swift)、シングルチャットとロボット(micro、Turing、Sizhi)のチャット機能を含む、TeamTalkやGuazi IMなどの有名なプロジェクトが完了し、現在グループチャット機能が実行されています。開発された、より多くの注意を払うためにフラッターテクノロジーのgolangとクロスプラットフォーム開発に興味を持っているWelcomefriendsStar。

————————————————
著作権表示:この記事はCSDNブロガー「XuFei」のオリジナル記事であり、CC 4.0BY-SA著作権表示に準拠しています。元のソースを添付してくださいリンクとこれを再印刷します。ステートメント。
元のリンク:https://blog.csdn.net/xmcy001122/article/details/109381059

おすすめ

転載: blog.csdn.net/xmcy001122/article/details/109381059