- MQTT(上报位置、订阅成员、收到消息更新成员列表对应信息)

This commit is contained in:
linshujie 2026-06-15 18:38:15 +08:00
parent 553374089a
commit 42502519f7
46 changed files with 3227 additions and 44 deletions

View File

@ -50,6 +50,7 @@ target 'QuickLocation' do
#第三方SDk
pod 'GYSDK' #个推一键登录
pod 'OpenIMSDK' #OpenIM
pod 'CocoaMQTT' #MQTT
#支付宝
pod 'AlipaySDK-iOS'

View File

@ -11,6 +11,10 @@ PODS:
- CocoaLumberjack/Core (3.9.1)
- CocoaLumberjack/Swift (3.9.1):
- CocoaLumberjack/Core
- CocoaMQTT (2.2.5):
- CocoaMQTT/Core (= 2.2.5)
- CocoaMQTT/Core (2.2.5):
- MqttCocoaAsyncSocket (~> 1.0.8)
- Differentiator (5.0.0)
- GTCommonSDK (3.2.3.0):
- ZXSDK
@ -89,6 +93,7 @@ PODS:
- Moya/Core (= 15.0.0)
- Moya/Core (15.0.0):
- Alamofire (~> 5.0)
- MqttCocoaAsyncSocket (1.0.8)
- ObjectMapper (4.4.2)
- "OpenIMSDK (3.8.3+hotfix.3.1)":
- MJExtension
@ -174,6 +179,7 @@ DEPENDENCIES:
- AMapLocation
- AMapSearch
- CocoaLumberjack/Swift
- CocoaMQTT
- GYSDK
- HXPHPicker
- IQKeyboardManagerSwift
@ -215,6 +221,7 @@ SPEC REPOS:
- AMapLocation
- AMapSearch
- CocoaLumberjack
- CocoaMQTT
- Differentiator
- GTCommonSDK
- GYSDK
@ -236,6 +243,7 @@ SPEC REPOS:
- MJExtension
- MJRefresh
- Moya
- MqttCocoaAsyncSocket
- ObjectMapper
- OpenIMSDK
- OpenIMSDKCore
@ -277,6 +285,7 @@ SPEC CHECKSUMS:
AMapLocation: 6e44f50b044dc54c6b3dcb1dee5ffd6de2689e41
AMapSearch: 29224a399b56b17da1540e4312fc4d9dc37342bb
CocoaLumberjack: e4ba3b414dfca8c1916c6303d37f63b3a95134c6
CocoaMQTT: 1e2fa493d57045d66fb1eba2bb5ffb8d77039c60
Differentiator: e8497ceab83c1b10ca233716d547b9af21b9344d
GTCommonSDK: 238c6735add91e654f8564638854686ee3dcb4ac
GYSDK: db5f4b3aae8df06201be5e786076211ec11791be
@ -299,6 +308,7 @@ SPEC CHECKSUMS:
MJExtension: e97d164cb411aa9795cf576093a1fa208b4a8dd8
MJRefresh: ff9e531227924c84ce459338414550a05d2aea78
Moya: 138f0573e53411fb3dc17016add0b748dfbd78ee
MqttCocoaAsyncSocket: 77d3b74f76228dd5a05d1f9526eab101d415b30c
ObjectMapper: e6e4d91ff7f2861df7aecc536c92d8363f4c9677
OpenIMSDK: c1880296ead605bcac2a289ad0aef9170fe6e6df
OpenIMSDKCore: 75caba22be8ee484011f367711178312bd64a17d
@ -323,6 +333,6 @@ SPEC CHECKSUMS:
YYImage: 1e1b62a9997399593e4b9c4ecfbbabbf1d3f3b54
ZXSDK: 786338c0a18e98e03eda00699c3bfd2700b97117
PODFILE CHECKSUM: 6ba8ada83ccc565c9bdcc418e9a936818640882c
PODFILE CHECKSUM: 861114200722c29adba98535aef6b0494d123b44
COCOAPODS: 1.16.2

View File

@ -188,6 +188,9 @@
30C4C01D2FDBF557009215C1 /* RemoveMemberViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C4C01C2FDBF557009215C1 /* RemoveMemberViewModel.swift */; };
30C4C0202FDC0EC5009215C1 /* GroupInfoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C4C01F2FDC0EC5009215C1 /* GroupInfoView.swift */; };
30C4C0222FDC0ED3009215C1 /* GroupInfoVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C4C0212FDC0ED3009215C1 /* GroupInfoVC.swift */; };
30D87CDB2FDFA9EE00E958FD /* MQTTService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D87CDA2FDFA9EE00E958FD /* MQTTService.swift */; };
30D87CDD2FDFF07500E958FD /* InteractionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D87CDC2FDFF07500E958FD /* InteractionView.swift */; };
30D87CDF2FDFF1A100E958FD /* QuickMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D87CDE2FDFF1A100E958FD /* QuickMessageView.swift */; };
30DC18522FD009CD0041DCD1 /* VipExpenseModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30DC18512FD009CD0041DCD1 /* VipExpenseModel.swift */; };
30DC18542FD00C4A0041DCD1 /* VipRechargeVM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30DC18532FD00C4A0041DCD1 /* VipRechargeVM.swift */; };
30DC185A2FD11E7A0041DCD1 /* WebOperations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30DC18562FD11E7A0041DCD1 /* WebOperations.swift */; };
@ -420,6 +423,9 @@
30C4C01C2FDBF557009215C1 /* RemoveMemberViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoveMemberViewModel.swift; sourceTree = "<group>"; };
30C4C01F2FDC0EC5009215C1 /* GroupInfoView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupInfoView.swift; sourceTree = "<group>"; };
30C4C0212FDC0ED3009215C1 /* GroupInfoVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupInfoVC.swift; sourceTree = "<group>"; };
30D87CDA2FDFA9EE00E958FD /* MQTTService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MQTTService.swift; sourceTree = "<group>"; };
30D87CDC2FDFF07500E958FD /* InteractionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InteractionView.swift; sourceTree = "<group>"; };
30D87CDE2FDFF1A100E958FD /* QuickMessageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuickMessageView.swift; sourceTree = "<group>"; };
30DC18512FD009CD0041DCD1 /* VipExpenseModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VipExpenseModel.swift; sourceTree = "<group>"; };
30DC18532FD00C4A0041DCD1 /* VipRechargeVM.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VipRechargeVM.swift; sourceTree = "<group>"; };
30DC18552FD11E7A0041DCD1 /* NavigationTitleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NavigationTitleView.swift; sourceTree = "<group>"; };
@ -472,6 +478,11 @@
path = lotties;
sourceTree = "<group>";
};
30D87CEF2FDFF52100E958FD /* TTGTagCollectionView */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = TTGTagCollectionView;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@ -765,6 +776,7 @@
305A75282FCA8C7000227D26 /* Notification */,
305A752A2FCA8C7000227D26 /* Theme */,
305A752C2FCA8C7000227D26 /* URL */,
30D87CD52FDF9F1900E958FD /* MQTT */,
);
path = Manager;
sourceTree = "<group>";
@ -852,6 +864,8 @@
305A76292FCA8C7000227D26 /* HomeViewController.swift */,
305A798B2FCAB99300227D26 /* HomeViewModel.swift */,
30A7A9102FCAEE3D00105780 /* GroupListPopView.swift */,
30D87CDE2FDFF1A100E958FD /* QuickMessageView.swift */,
30D87CDC2FDFF07500E958FD /* InteractionView.swift */,
);
path = Home;
sourceTree = "<group>";
@ -1032,6 +1046,7 @@
305A767D2FCA8C7000227D26 /* UIKit */ = {
isa = PBXGroup;
children = (
30D87CEF2FDFF52100E958FD /* TTGTagCollectionView */,
305A76482FCA8C7000227D26 /* Alert */,
305A76502FCA8C7000227D26 /* EmptyDataSet */,
305A76542FCA8C7000227D26 /* HUD */,
@ -1174,6 +1189,14 @@
path = GroupInfo;
sourceTree = "<group>";
};
30D87CD52FDF9F1900E958FD /* MQTT */ = {
isa = PBXGroup;
children = (
30D87CDA2FDFA9EE00E958FD /* MQTTService.swift */,
);
path = MQTT;
sourceTree = "<group>";
};
30DC18582FD11E7A0041DCD1 /* Controller */ = {
isa = PBXGroup;
children = (
@ -1313,6 +1336,7 @@
);
fileSystemSynchronizedGroups = (
3070777D2FD2A214004C37CC /* lotties */,
30D87CEF2FDFF52100E958FD /* TTGTagCollectionView */,
);
name = QuickLocation;
productName = QuickLocation;
@ -1457,6 +1481,7 @@
30C4C0222FDC0ED3009215C1 /* GroupInfoVC.swift in Sources */,
305A76902FCA8C7000227D26 /* UserAPI.swift in Sources */,
30EFF3DE2FDA982C00EB35D4 /* EmergencyContactAddVC.swift in Sources */,
30D87CDF2FDFF1A100E958FD /* QuickMessageView.swift in Sources */,
305A76912FCA8C7000227D26 /* Constant.swift in Sources */,
305A76922FCA8C7000227D26 /* LogUtils.swift in Sources */,
305A76932FCA8C7000227D26 /* AddImageCell.swift in Sources */,
@ -1620,6 +1645,7 @@
305A76FB2FCA8C7000227D26 /* EmptyDataSet.swift in Sources */,
305A76FC2FCA8C7000227D26 /* EmptyDataSetDelegate.swift in Sources */,
305A76FD2FCA8C7000227D26 /* EmptyDataSetSource.swift in Sources */,
30D87CDB2FDFA9EE00E958FD /* MQTTService.swift in Sources */,
30EFF3CD2FDA668A00EB35D4 /* MyProfileView.swift in Sources */,
305A76FE2FCA8C7000227D26 /* EmptyDataSetView.swift in Sources */,
30C4C0192FDBF094009215C1 /* RemoveMemberVC.swift in Sources */,
@ -1630,6 +1656,7 @@
305A77032FCA8C7000227D26 /* ProgressHUD.swift in Sources */,
305A77042FCA8C7000227D26 /* MXParallaxHeader.m in Sources */,
305A77052FCA8C7000227D26 /* MXScrollView.m in Sources */,
30D87CDD2FDFF07500E958FD /* InteractionView.swift in Sources */,
30BAB8652FCD718A00C33B5C /* JoinGroupView.swift in Sources */,
305A77062FCA8C7000227D26 /* MXScrollViewController.m in Sources */,
305A77072FCA8C7000227D26 /* Helper.swift in Sources */,

View File

@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "Group_1572@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "Group_1572@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 712 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "interaction_header@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "interaction_header@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

View File

@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "Group_1951@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "Group_1951@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

View File

@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "Group_1947@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "Group_1947@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -79,6 +79,11 @@ final class MainTabBarController: UITabBarController {
guard let nav = selectedViewController as? UINavigationController else { return }
customTabBar.isHidden = nav.viewControllers.count > 1
}
/// 强制显示/隐藏 tabBar(供底部面板使用)
func setTabBarHidden(_ hidden: Bool) {
customTabBar.isHidden = hidden
}
}
// MARK: - QuickLocationTabBarDelegate

View File

@ -0,0 +1,257 @@
//
// MQTTService.swift
// QuickLocation
//
// Created by 八条 on 2026/6/12.
//
import Foundation
import CocoaMQTT
import UIKit
import _LocationEssentials
// MARK: - MQTT 模型
/// 位置上报类型
enum MqttType: String, Codable {
case track = "track" // 追踪(获取)和更新用户状态
case disconnect = "disconnect"
case message = "message"
case join = "join" // 加入群
case leave = "leave" // 离开群
case dismiss = "dismiss" // 解散群
case kick = "kick" // 踢人
case signIn = "signin" // 签到
case sos = "sos" // 求助
case needTrack = "needtrack" // 追踪上报
case emote = "emote" // 接收表情
}
/// 单点位置
struct Points: Codable {
let lat: Double
let lon: Double
let addr: String
let time: Int64 // 毫秒时间戳
let speed: Double
let bearing: Double
let altitude: Double
let accuracy: Double
}
/// 位置上报数据(发送)
struct MqttLocation: Codable {
let battery: String
let points: [Points]
}
/// MQTT 收到的位置消息(接收解析用)
struct MqttIncomingMessage: Decodable {
let type: String?
let data: MqttIncomingData?
let extra: String?
}
struct MqttIncomingData: Decodable {
let points: [Points]?
let battery: String?
}
// MARK: - MQTTService
/// MQTT 5.0 服务,管理连接、订阅和消息收发
final class MQTTService: NSObject {
static let shared = MQTTService()
private var mqtt: CocoaMQTT5?
private var isConnected = false
// MARK: - 连接状态回调
var onConnected: (() -> Void)?
var onDisconnected: (() -> Void)?
/// 全局接收回调(所有未匹配 topicCallback 的消息)
var onMessageReceived: ((CocoaMQTT5Message, UInt16, MqttPublishProperties) -> Void)?
/// 按 topic 订阅的回调(优先匹配)
private var topicCallbacks: [String: (CocoaMQTT5Message) -> Void] = [:]
// MARK: - 配置
private var host: String { "emqx.batiao8.com" }
private var port: UInt16 { 1883 }
/// 当前 clientID,切换用户时可更新后重连
private(set) var clientID: String = ""
private var userName = "batiao"
private var password = "Batiao12B"
private var topic = "smartdrive/"
override private init() {}
// MARK: - 连接
func connect() {
guard !isConnected else { return }
if clientID.isEmpty {
clientID = "smartdrive_\(AppContextManager.shared.userId)"
}
let mqtt = CocoaMQTT5(clientID: clientID, host: host, port: port)
mqtt.username = userName
mqtt.password = password
mqtt.keepAlive = 60
mqtt.autoReconnect = true
mqtt.autoReconnectTimeInterval = 5
mqtt.delegate = self
mqtt.logLevel = .warning
self.mqtt = mqtt
_ = mqtt.connect()
}
// MARK: - 断开
func disconnect() {
mqtt?.disconnect()
isConnected = false
}
// MARK: - 切换用户
/// 更新 clientID 并重连(切换用户后调用)
func updateClientID(_ newID: String) {
clientID = newID
disconnect()
connect()
}
// MARK: - 订阅主题
/// - Parameters:
/// - topic: 主题
/// - qos: 服务质量
/// - callback: 可选,该 topic 的专用回调,收到消息时优先于此回调
func subscribe(topic: String, qos: CocoaMQTTQoS = .qos1, callback: ((CocoaMQTT5Message) -> Void)? = nil) {
let subscription = MqttSubscription(topic: topic, qos: qos)
mqtt?.subscribe([subscription])
if let cb = callback {
topicCallbacks[topic] = cb
}
}
// MARK: - 取消订阅
func unsubscribe(topic: String) {
mqtt?.unsubscribe(topic)
topicCallbacks.removeValue(forKey: topic)
}
/// 订阅指定圈子的所有成员位置 topic: smartdrive/<memberId>
func subscribeGroupMembers(_ memberIds: [String]) {
for id in memberIds {
subscribe(topic: "\(topic)\(id)")
}
}
/// 取消订阅上一批成员
func unsubscribeGroupMembers(_ memberIds: [String]) {
for id in memberIds {
mqtt?.unsubscribe("\(topic)\(id)")
}
}
// MARK: - 发布消息
@discardableResult
func publish(topic: String, message: String, qos: CocoaMQTTQoS = .qos1) -> Int {
let properties = MqttPublishProperties()
return mqtt?.publish(topic, withString: message, qos: qos, DUP: false, retained: false, properties: properties) ?? -1
}
@discardableResult
func publish(topic: String, data: Data, qos: CocoaMQTTQoS = .qos1) -> Int {
let properties = MqttPublishProperties()
let message = CocoaMQTT5Message(topic: topic, payload: [UInt8](data))
return mqtt?.publish(message, DUP: false, retained: false, properties: properties) ?? -1
}
// MARK: - 位置上报
/// 构建并上报位置数据(格式与 Android 一致)
func reportLocation(lat: Double, lon: Double, addr: String,
speed: CLLocationSpeed, bearing: CLLocationDirection,
altitude: CLLocationDistance, accuracy: CLLocationAccuracy) {
let battery = UIDevice.current.batteryLevel > 0
? Int(UIDevice.current.batteryLevel * 100)
: 0
let point = Points(
lat: lat, lon: lon, addr: addr,
time: Int64(Date().timeIntervalSince1970 * 1000),
speed: speed, bearing: bearing,
altitude: altitude, accuracy: accuracy
)
let location = MqttLocation(battery: battery.string, points: [point])
guard let jsonData = try? JSONEncoder().encode(location),
let dataDict = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
else { return }
// 外层包装,data 是 JSON 对象而非字符串
let payload: [String: Any] = [
"type": MqttType.track.rawValue,
"extra": "",
"data": dataDict
]
publish(topic: "\(topic)\(AppContextManager.shared.userId)", message: payload.toJsonString())
}
}
// MARK: - CocoaMQTT5Delegate
extension MQTTService: CocoaMQTT5Delegate {
func mqtt5(_ mqtt5: CocoaMQTT5, didConnectAck ack: CocoaMQTTCONNACKReasonCode, connAckData: MqttDecodeConnAck?) {
isConnected = true
print("MQTT5 connected: \(ack)")
onConnected?()
}
func mqtt5(_ mqtt5: CocoaMQTT5, didPublishMessage message: CocoaMQTT5Message, id: UInt16) {
print("MQTT5 published: \(message.topic)")
}
func mqtt5(_ mqtt5: CocoaMQTT5, didPublishAck id: UInt16, pubAckData: MqttDecodePubAck?) {
print("MQTT5 publish ack: \(id)")
}
func mqtt5(_ mqtt5: CocoaMQTT5, didPublishRec id: UInt16, pubRecData: MqttDecodePubRec?) {}
func mqtt5(_ mqtt5: CocoaMQTT5, didReceiveMessage message: CocoaMQTT5Message, id: UInt16, publishData: MqttDecodePublish?) {
// 优先 topic 专用回调
if let cb = topicCallbacks[message.topic] {
cb(message)
return
}
// 没有专用回调时走全局回调
if let payload = message.string {
print("MQTT5 received on \(message.topic): \(payload)")
}
onMessageReceived?(message, id, MqttPublishProperties())
}
func mqtt5(_ mqtt5: CocoaMQTT5, didSubscribeTopics success: NSDictionary, failed: [String], subAckData: MqttDecodeSubAck?) {
print("MQTT5 subscribe success: \(success), failed: \(failed)")
}
func mqtt5(_ mqtt5: CocoaMQTT5, didUnsubscribeTopics topics: [String], unsubAckData: MqttDecodeUnsubAck?) {
print("MQTT5 unsubscribe: \(topics)")
}
func mqtt5(_ mqtt5: CocoaMQTT5, didReceiveDisconnectReasonCode reasonCode: CocoaMQTTDISCONNECTReasonCode) {}
func mqtt5(_ mqtt5: CocoaMQTT5, didReceiveAuthReasonCode reasonCode: CocoaMQTTAUTHReasonCode) {}
func mqtt5DidPing(_ mqtt5: CocoaMQTT5) {}
func mqtt5DidReceivePong(_ mqtt5: CocoaMQTT5) {}
func mqtt5DidDisconnect(_ mqtt5: CocoaMQTT5, withError err: Error?) {
isConnected = false
print("MQTT5 disconnected: \(err?.localizedDescription ?? "")")
onDisconnected?()
}
}

View File

@ -185,6 +185,8 @@ struct GroupMemberModel: Mappable, Equatable {
}
/// 是否在线
var is_online: Bool = false
/// 最后在线文本(MQTT 计算)
var lastUpdateText: String = ""
/// 设备电量
var battery: String = ""
/// 最后在线时间

View File

@ -17,6 +17,8 @@
#import "MXScrollView.h"
#import "MXScrollViewController.h"
#import "TTGTextTagCollectionView.h"
// Pop
#import "DLViewTransition.h"

View File

@ -30,7 +30,7 @@ class GroupInfoVC: BaseViewController {
rootView.groupIcon.image = model.groupIcon
rootView.groupNameLab.text = model.name
rootView.setupData(model)
rootView.applyBtn.rx.tap.subscribe(onNext: { _ in
self.requestOperateGroup()
}).disposed(by: disposeBag)

View File

@ -8,11 +8,21 @@
import UIKit
import RxSwift
import RxCocoa
import TagListView
class GroupInfoView: UIView {
var disposeBag = DisposeBag()
func setupData(_ model: GroupInfoModel) {
groupDescLab.text = model.description.isEmpty ? "暂无描述" : model.description
tagListView.addTags(model.labels)
tagListView.tagViews.forEach {
$0.layer.cornerRadius = 4
}
tagListView.invalidateIntrinsicContentSize() // 通知系统重新算高
}
private func setupRx() {
backBtn.rx.tap.subscribe(onNext: { _ in
@ -28,6 +38,8 @@ class GroupInfoView: UIView {
addSubview(groupIcon)
addSubview(groupNameLab)
addSubview(groupDescView)
addSubview(tagView)
addSubview(applyBtn)
navBgView.layoutChain
@ -59,6 +71,14 @@ class GroupInfoView: UIView {
.topToBottomOfView(groupIcon, offset: 4)
.centerX()
groupDescView.layoutChain
.topToBottomOfView(groupNameLab, offset: 30)
.edgesHorzontal(15)
tagView.layoutChain
.topToBottomOfView(groupDescView, offset: 10)
.edgesHorzontal(15)
applyBtn.layoutChain
.edgesHorzontal(30)
.bottom(kSafeBottomMargin + 10)
@ -108,6 +128,78 @@ class GroupInfoView: UIView {
return label
}()
lazy var groupDescView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexStr: "#F5FBFF")
view.cornerRadius = 10
let titleLab = UILabel()
titleLab.text = "圈子描述"
titleLab.textColor = ThemeManager.shared.color.titleAuxColor
titleLab.font = .systemFont(ofSize: 12, weight: .medium)
view.addSubview(titleLab)
titleLab.layoutChain
.left(15)
.width(50)
.top(22)
view.addSubview(groupDescLab)
groupDescLab.layoutChain
.top(20)
.leftToRightOfView(titleLab, offset: 20)
.right(15)
.bottom(20)
return view
}()
lazy var groupDescLab: UILabel = {
let label = UILabel()
label.textColor = ThemeManager.shared.color.titleAuxColor
label.font = .systemFont(ofSize: 14, weight: .medium)
label.numberOfLines = 0
return label
}()
// 标签
lazy var tagView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexStr: "#F5FBFF")
view.cornerRadius = 10
let titleLab = UILabel()
titleLab.text = "圈子标签"
titleLab.textColor = ThemeManager.shared.color.titleAuxColor
titleLab.font = .systemFont(ofSize: 12, weight: .medium)
view.addSubview(titleLab)
titleLab.layoutChain
.left(15)
.width(50)
.top(20)
view.addSubview(tagListView)
tagListView.layoutChain
.top(15)
.leftToRightOfView(titleLab, offset: 23)
.height(27, relation: .greaterThanOrEqual)
.right(15)
.bottom(20)
return view
}()
lazy var tagListView: TagListView = {
let view = TagListView()
view.textFont = UIFont.systemFont(ofSize: 12, weight: .medium)
view.textColor = UIColor(hexStr: "#16B3FF")
view.tagBackgroundColor = UIColor(hexStr: "#E3F6FF")
view.paddingX = 20 // 水平内边距
view.paddingY = 6 // 垂直内边距
view.alignment = .left // 对齐
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var applyBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("申请加入", for: .normal)

View File

@ -135,6 +135,7 @@ class GroupMemberView: UIView {
tableView.estimatedRowHeight = 76
tableView.bounces = false
tableView.showsVerticalScrollIndicator = false
tableView.isScrollEnabled = false
tableView.register(GroupMemberCell.self)
return tableView
}()
@ -165,12 +166,24 @@ class GroupMemberCell: UITableViewCell {
nameLab.textColor = UIColor(hexStr: isCurrentUser ? "#16B3FF" : "#0F2846")
// 电量 16是电池图标宽度,右边有电池造型需要减去
batteryView.layoutChain.width(CGFloat((16 - 1) * (model.battery.int / 100)))
let batteryPercent = min(CGFloat(model.battery.int), 100)
batteryView.layoutChain.width(CGFloat(16 - 1) * batteryPercent / 100.0)
batteryLab.text = "\(model.battery)%"
// 在线状态
if model.is_online {
onlineDotView.isHidden = false
onlineStatusLab.text = "在线"
onlineStatusLab.textColor = ThemeManager.shared.color.titleAuxColor
} else {
onlineDotView.isHidden = true
onlineStatusLab.text = model.lastUpdateText
onlineStatusLab.textColor = UIColor(hexStr: "#999999")
}
}
private func setupSubviews() {
contentView.addSubview(ownBgView)
contentView.addSubview(selectedBgView)
contentView.addSubview(avaterImgView)
contentView.addSubview(vipIcon)
contentView.addSubview(batteryInfoView)
@ -188,7 +201,7 @@ class GroupMemberCell: UITableViewCell {
}
private func setupLayout() {
ownBgView.layoutChain
selectedBgView.layoutChain
.edgesHorzontal(15)
.edgesVertical()
@ -212,7 +225,7 @@ class GroupMemberCell: UITableViewCell {
.width(16)
.height(8)
batteryView.layoutChain
batteryView.layoutChain
.topToView(batteryIcon)
.leftToView(batteryIcon, offset: -1)
.bottomToView(batteryIcon)
@ -256,7 +269,7 @@ class GroupMemberCell: UITableViewCell {
.bottom(18)
}
lazy var ownBgView: UIView = {
lazy var selectedBgView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexStr: "#EAFBFF")
view.cornerRadius = 10
@ -387,32 +400,38 @@ class GroupMemberCell: UITableViewCell {
let view = UIView()
view.backgroundColor = .clear
let dot = UIView()
dot.backgroundColor = UIColor(hexStr: "#67EA76")
dot.cornerRadius = 4
view.addSubview(onlineDotView)
view.addSubview(onlineStatusLab)
let label = UILabel()
label.textColor = ThemeManager.shared.color.titleAuxColor
label.font = .systemFont(ofSize: 10, weight: .medium)
label.text = "在线"
view.addSubview(dot)
view.addSubview(label)
dot.layoutChain
onlineDotView.layoutChain
.left()
.centerY()
.height(8)
.width(8)
label.layoutChain
onlineStatusLab.layoutChain
.edgesVertical()
.leftToRightOfView(dot, offset: 3)
.leftToRightOfView(onlineDotView, offset: 3)
.right()
return view
}()
lazy var onlineDotView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexStr: "#67EA76")
view.cornerRadius = 4
return view
}()
lazy var onlineStatusLab: UILabel = {
let label = UILabel()
label.textColor = ThemeManager.shared.color.titleAuxColor
label.font = .systemFont(ofSize: 10, weight: .medium)
label.text = "在线"
return label
}()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
@ -431,7 +450,6 @@ class GroupMemberCell: UITableViewCell {
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
selectedBgView.isHidden = !selected
}
}

View File

@ -19,12 +19,18 @@ class HomeView: UIView {
let groupMemberView = GroupMemberView(frame: .zero)
let quickMessageView = QuickMessageView(frame: CGRectMake(0, kScreenHeight, kScreenWidth, 93))
let interactionView = InteractionView(frame: CGRectMake(0, kScreenHeight, kScreenWidth, 384))
// MARK: - groupMemberView 拖拽
private var groupMemberTopConstraint: NSLayoutConstraint?
private var groupMemberUpLimit: CGFloat = 0
private var groupMemberDownLimit: CGFloat = 0
private var isGroupMemberLimitsSet = false
private var panStartTop: CGFloat = 0
/// 内嵌 tableView 是否可滑动(最大化时才可)
private var isSubCanScroll = false
// MARK: - Map
#if !targetEnvironment(simulator)
@ -58,9 +64,37 @@ class HomeView: UIView {
}()
#endif
/// 面板关闭回调
var onDismissPanel: (() -> Void)?
// MARK: - Setup
private func setupRx() {
quickMessageView.closeBtn.rx.tap
.subscribe(onNext: { [weak self] _ in
self?.dismissMemberPanel()
self?.onDismissPanel?()
})
.disposed(by: disposeBag)
// tableView 到达顶部继续下拉时,改由 GroupMemberView 的 pan 手势接管
groupMemberView.tableView.rx.contentOffset
.subscribe(onNext: { [weak self] offset in
guard let self = self else { return }
if self.isSubCanScroll {
if offset.y <= 0 {
self.isSubCanScroll = false
self.groupMemberView.tableView.setContentOffset(.zero, animated: false)
}
} else if offset.y != 0 {
self.groupMemberView.tableView.setContentOffset(.zero, animated: false)
}
})
.disposed(by: disposeBag)
// 收回互动view
quickMessageView.closeBtn.rx.tap.subscribe(onNext: { _ in
self.dismissMemberPanel()
}).disposed(by: disposeBag)
}
private func setupUI() {
@ -206,7 +240,29 @@ class HomeView: UIView {
)
let pan = UIPanGestureRecognizer(target: self, action: #selector(handleGroupMemberPan(_:)))
pan.delegate = self
groupMemberView.addGestureRecognizer(pan)
// 底部弹出面板(quickMessageView 在上,interactionView 在下)
addSubview(interactionView)
addSubview(quickMessageView)
}
// MARK: - 底部面板显隐
func showMemberPanel(member: CircleMember) {
interactionView.configure(member: member)
quickMessageView.isHidden = false
interactionView.isHidden = false
quickMessageView.frame.origin.y = kScreenHeight - 384 - 93
interactionView.frame.origin.y = kScreenHeight - 384
}
func dismissMemberPanel() {
quickMessageView.frame.origin.y = kScreenHeight
interactionView.frame.origin.y = kScreenHeight
quickMessageView.isHidden = true
interactionView.isHidden = true
onDismissPanel?()
}
override init(frame: CGRect) {
@ -239,10 +295,24 @@ class HomeView: UIView {
switch pan.state {
case .began:
panStartTop = pan.location(in: self).y - pan.translation(in: self).y
panStartTop = groupMemberView.frame.minY
case .changed:
let newTop = panStartTop + pan.translation(in: self).y
// 最大化状态下,tableView 可以向下滑时,不干扰自身滑动;
// 只有 tableView 到达顶部继续下拉时,才切换为 view 拖拽
if isSubCanScroll {
let tableViewOffset = self.groupMemberView.tableView.contentOffset.y
if tableViewOffset > 0, newTop >= groupMemberUpLimit {
// 还未滑到顶部,让 tableView 处理
return
}
// 到达顶部继续下拉 → 关闭子滚动,交由 view 的 pan 处理
isSubCanScroll = false
panStartTop = groupMemberView.frame.minY
}
let clamped = max(groupMemberUpLimit, min(groupMemberDownLimit, newTop))
topConstraint.constant = clamped - groupMemberDownLimit + 10
@ -260,6 +330,13 @@ class HomeView: UIView {
UIView.animate(withDuration: 0.25, delay: 0,
options: [.curveEaseOut, .allowUserInteraction]) {
self.layoutIfNeeded()
} completion: { _ in
let atTop = target == self.groupMemberUpLimit
self.isSubCanScroll = atTop
// 未最大化时重置 tableView 到顶部
if !atTop {
self.groupMemberView.tableView.contentOffset.y = 0
}
}
default:
@ -267,6 +344,17 @@ class HomeView: UIView {
}
}
/// 收起 GroupMemberView(选中成员后调用)
func dismissGroupMemberView() {
guard isGroupMemberLimitsSet, let topConstraint = groupMemberTopConstraint else { return }
isSubCanScroll = false
topConstraint.constant = groupMemberDownLimit - groupMemberDownLimit + 10
groupMemberView.tableView.setContentOffset(.zero, animated: false)
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut) {
self.layoutIfNeeded()
}
}
// MARK: - UI Components
lazy var navBarBg: UIImageView = {
let view = UIImageView()
@ -482,3 +570,13 @@ class HomeView: UIView {
return view
}()
}
// MARK: - UIGestureRecognizerDelegate
extension HomeView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
// 允许 GroupMemberView 的 pan 与 tableView 的 pan 同时识别
// 滚动状态由 isSubCanScroll + contentOffset 控制,不影响手势判定
return true
}
}

View File

@ -14,6 +14,7 @@ import SwiftyUserDefaults
#if !targetEnvironment(simulator)
import MAMapKit
import CocoaMQTT
#endif
class HomeViewController: BaseViewController {
@ -35,6 +36,13 @@ class HomeViewController: BaseViewController {
private var members: [CircleMember] = []
private var currentUserMember: CircleMember?
private var currentUserAnnotation: MemberAnnotation?
/// 最新位置(供 MQTT 定时上报)
private var lastLocation: CLLocation?
private var locationTimer: Timer?
/// 当前已订阅 MQTT 的成员 ID 列表
private var subscribedMemberIds: [String] = []
/// 底部成员面板是否显示
private var isMemberPanelShown = false
override func loadView() {
#if !targetEnvironment(simulator)
@ -54,9 +62,60 @@ class HomeViewController: BaseViewController {
reactiveAction()
requestUserConfig()
// MQTT 位置上报
UIDevice.current.isBatteryMonitoringEnabled = true
startLocationTimer()
}
// MARK: - MQTT 位置上报
private let geocoder = CLGeocoder()
private var lastGeocodedCoord: CLLocationCoordinate2D?
private var lastAddress: String = ""
private func startLocationTimer() {
locationTimer?.invalidate()
locationTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
guard let self = self, let loc = self.lastLocation else { return }
let coord = loc.coordinate
// 坐标变化不大时复用上次地址
if let last = self.lastGeocodedCoord,
hypot(coord.latitude - last.latitude, coord.longitude - last.longitude) < 0.001,
!self.lastAddress.isEmpty {
self.publishLocation(coord: coord, address: self.lastAddress, loc: loc)
return
}
// 反向地理编码获取地址
self.geocoder.reverseGeocodeLocation(loc) { [weak self] placemarks, error in
guard let self = self else { return }
let address = placemarks?.first?.name
?? placemarks?.first?.thoroughfare
?? placemarks?.first?.locality
?? ""
self.lastAddress = address
self.lastGeocodedCoord = coord
self.publishLocation(coord: coord, address: address, loc: loc)
}
}
}
private func publishLocation(coord: CLLocationCoordinate2D, address: String, loc: CLLocation) {
MQTTService.shared.reportLocation(
lat: coord.latitude,
lon: coord.longitude,
addr: address,
speed: loc.speed,
bearing: loc.course,
altitude: loc.altitude,
accuracy: loc.horizontalAccuracy
)
}
// MARK: - Actions
private func reactiveAction() {
rootView.groupView.rx.tapGesture.subscribe { _ in
guard let groupModel = self.viewModel.groupModel else { return }
let groupViewFrame = self.view.convert(self.rootView.groupView.frame, from: self.rootView)
@ -93,6 +152,17 @@ class HomeViewController: BaseViewController {
.subscribe { [weak self] notification in
self?.requestGroupInfo()
}.disposed(by: disposeBag)
// 面板关闭回调
rootView.onDismissPanel = { [weak self] in
self?.isMemberPanelShown = false
(self?.tabBarController as? MainTabBarController)?.setTabBarHidden(false)
}
// MQTT 接收
MQTTService.shared.onMessageReceived = { message, id, properties in
print("收到消息: \(message.string ?? "")")
}
}
private func bindViewModel() {
@ -100,9 +170,20 @@ class HomeViewController: BaseViewController {
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx.modelSelected(GroupMemberModel.self)
let selectedMember = tableView.rx.modelSelected(GroupMemberModel.self)
.share()
selectedMember
.subscribe(viewModel.cellAction.inputs)
.disposed(by: disposeBag)
// 选中成员 → 地图定位
selectedMember
.subscribe(onNext: { [weak self] model in
guard let self = self else { return }
self.locateMember(userId: model.user_id)
})
.disposed(by: disposeBag)
}
// MARK: - UITableViewDataSource
@ -161,6 +242,7 @@ class HomeViewController: BaseViewController {
self.rootView.groupMemberView.setupCountData(self.viewModel.memberCount, self.viewModel.memberOnlineCount)
self.rootView.groupNameLab.text = self.viewModel.groupName
self.syncMemberAnnotations(model.select_group_employee)
self.refreshMQTTSubscriptions(model.select_group_employee)
}.disposed(by: disposeBag)
}
@ -175,6 +257,11 @@ class HomeViewController: BaseViewController {
#if !targetEnvironment(simulator)
rootView.mapView.delegate = self
// 地图点击选择标注
let mapTap = UITapGestureRecognizer(target: self, action: #selector(handleMapTap(_:)))
mapTap.cancelsTouchesInView = false
rootView.mapView.addGestureRecognizer(mapTap)
let r = MAUserLocationRepresentation()
r.showsAccuracyRing = false
r.showsHeadingIndicator = false
@ -188,6 +275,23 @@ class HomeViewController: BaseViewController {
#endif
}
@objc private func handleMapTap(_ tap: UITapGestureRecognizer) {
let point = tap.location(in: rootView.mapView)
// 用 mapView 的坐标转屏幕坐标判断命中
for ann in rootView.mapView.annotations?.compactMap({ $0 as? MemberAnnotation }) ?? [] {
guard !ann.member.isCurrentUser else { continue }
let pt = rootView.mapView.convert(ann.coordinate, toPointTo: rootView.mapView)
// 30pt 命中半径
let hitRect = CGRect(x: pt.x - 30, y: pt.y - 30, width: 60, height: 60)
if hitRect.contains(point) {
self.isMemberPanelShown = true
(self.tabBarController as? MainTabBarController)?.setTabBarHidden(true)
rootView.showMemberPanel(member: ann.member)
break
}
}
}
private func transparentImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
let img = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
@ -227,7 +331,8 @@ class HomeViewController: BaseViewController {
coordinate: kCLLocationCoordinate2DInvalid,
address: "",
heading: 0,
lastUpdateText: "在线"
lastUpdateText: "在线",
battery: ""
)
// 其他成员从 select_group_employee 取,过滤掉当前用户
@ -255,6 +360,105 @@ class HomeViewController: BaseViewController {
mapView.addAnnotations(annotations)
#endif
}
#if !targetEnvironment(simulator)
/// 选中成员后地图定位到该成员,收起 GroupMemberView
private func locateMember(userId: String) {
rootView.dismissGroupMemberView()
guard let member = members.first(where: { $0.id == userId }),
CLLocationCoordinate2DIsValid(member.coordinate) else { return }
rootView.mapView.setCenter(member.coordinate, animated: true)
rootView.mapView.setZoomLevel(16, animated: true)
}
#endif
}
// MARK: - MQTT
extension HomeViewController {
/// 切换圈子时刷新 MQTT 订阅(排除当前用户)
private func refreshMQTTSubscriptions(_ members: [GroupMemberModel]) {
let currentId = AppContextManager.shared.userId
let newIds = members.map { $0.user_id }.filter { $0 != currentId }
let toUnsub = subscribedMemberIds.filter { !newIds.contains($0) }
MQTTService.shared.unsubscribeGroupMembers(toUnsub)
let toSub = newIds.filter { !subscribedMemberIds.contains($0) }
for memberId in toSub {
let topic = "smartdrive/\(memberId)"
MQTTService.shared.subscribe(topic: topic) { [weak self] message in
self?.handleMemberLocation(topic: message.topic, payload: message.string)
}
}
subscribedMemberIds = newIds
}
/// 处理成员位置更新(从 topic 提取 userId,更新地图标注)
private func handleMemberLocation(topic: String, payload: String?) {
guard let payload = payload,
let data = payload.data(using: .utf8),
let msg = try? JSONDecoder().decode(MqttIncomingMessage.self, from: data),
let firstPoint = msg.data?.points?.first
else { return }
print("📩 收到消息 -> 主题:\(topic),内容:\(msg)")
let userId = topic.replacingOccurrences(of: "smartdrive/", with: "")
let coord = CLLocationCoordinate2D(latitude: firstPoint.lat, longitude: firstPoint.lon)
guard CLLocationCoordinate2DIsValid(coord) else { return }
// 根据 time 字段判断在线状态(毫秒时间戳)
let nowMs = Date().timeIntervalSince1970 * 1000
let msgTimeMs = Double(firstPoint.time)
let diffSec = (nowMs - msgTimeMs) / 1000
let isOnline = diffSec < 60
let lastUpdateText: String
if isOnline {
lastUpdateText = ""
} else if diffSec < 3600 {
lastUpdateText = "\(Int(diffSec / 60))分钟前"
} else if diffSec < 86400 {
lastUpdateText = "\(Int(diffSec / 3600))小时前"
} else {
lastUpdateText = "\(Int(diffSec / 86400))天前"
}
let battery = msg.data?.battery ?? ""
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
// 更新列表(地址、电量、在线状态)
self.viewModel.updateMemberLocation(
userId: userId, lat: firstPoint.lat, lon: firstPoint.lon,
address: firstPoint.addr, battery: battery,
isOnline: isOnline, lastUpdateText: lastUpdateText
)
// 更新地图标注位置
self.updateAnnotation(userId: userId, coordinate: coord, address: firstPoint.addr)
}
}
/// 更新指定成员的标注位置(只更新坐标,头像/名称不变)
private func updateAnnotation(userId: String, coordinate: CLLocationCoordinate2D, address: String) {
#if !targetEnvironment(simulator)
// 更新 members 数组
if let idx = members.firstIndex(where: { $0.id == userId }) {
let old = members[idx]
members[idx] = CircleMember(
id: old.id, name: old.name, avatar: old.avatar,
isOnline: true, isOwner: old.isOwner,
coordinate: coordinate, address: address,
heading: old.heading, lastUpdateText: "在线",
battery: old.battery
)
}
// 更新地图标注坐标
let mapView = rootView.mapView
for ann in mapView.annotations?.compactMap({ $0 as? MemberAnnotation }) ?? [] {
if ann.member.id == userId {
ann.coordinate = coordinate
break
}
}
#endif
}
}
#if !targetEnvironment(simulator)
@ -278,6 +482,8 @@ extension HomeViewController: MAMapViewDelegate {
annotationView?.configure(with: memberAnnotation.member)
if memberAnnotation.member.isCurrentUser {
currentUserAnnotation = memberAnnotation
annotationView?.updateHeading(currentHeading)
@ -288,6 +494,7 @@ extension HomeViewController: MAMapViewDelegate {
func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
guard updatingLocation, let location = userLocation.location else { return }
lastLocation = location
let coordinate = location.coordinate
guard CLLocationCoordinate2DIsValid(coordinate) else { return }
@ -295,13 +502,30 @@ extension HomeViewController: MAMapViewDelegate {
ann.coordinate = coordinate
}
mapView.setCenter(coordinate, animated: true)
mapView.setUserTrackingMode(.follow, animated: true)
if !isMemberPanelShown {
mapView.setCenter(coordinate, animated: true)
mapView.setUserTrackingMode(.follow, animated: true)
}
}
func mapViewRequireLocationAuth(_ locationManager: CLLocationManager!) {
locationManager.requestAlwaysAuthorization()
}
func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
guard let annotationView = view as? MemberAnnotationView,
let annotation = annotationView.annotation as? MemberAnnotation,
!annotation.member.isCurrentUser else { return }
// 弹出底部面板
rootView.showMemberPanel(member: annotation.member)
}
func mapView(_ mapView: MAMapView!, didDeselect view: MAAnnotationView!) {
guard let annotationView = view as? MemberAnnotationView,
let annotation = annotationView.annotation as? MemberAnnotation,
!annotation.member.isCurrentUser else { return }
rootView.dismissMemberPanel()
}
}
#endif

View File

@ -32,7 +32,7 @@ class HomeViewModel {
var groupModel: GroupModel? {
didSet {
guard let model = groupModel else { return }
loadGroupMemberList(model.select_group_employee)
self.memberList = model.select_group_employee
}
}
@ -80,12 +80,37 @@ class HomeViewModel {
return model.default_group_key.contains(id)
}
func loadGroupMemberList(_ list: [GroupMemberModel]) {
// 调整圈子成为位置 圈主 -> 本人 -> 成员
var tempList = list
tempList.moveToFirst { $0.user_id == AppContextManager.shared.userId }
tempList.moveToFirst { isGroupOwn(id: $0.user_id) }
sectionedItems.onNext(tempList.mapSection())
var memberList: [GroupMemberModel] = [] {
didSet {
var tempList = memberList
// 当前用户的电量
// if var model = memberList.first(where: { $0.user_id == AppContextManager.shared.userId }),
// let idx = memberList.firstIndex(where: { $0.user_id == AppContextManager.shared.userId }) {
// let battery = UIDevice.current.batteryLevel > 0
// ? Int(UIDevice.current.batteryLevel * 100)
// : 0
// model.battery = battery.string
// model.is_online = true
// tempList[idx] = model
// }
tempList.moveToFirst { $0.user_id == AppContextManager.shared.userId }
tempList.moveToFirst { isGroupOwn(id: $0.user_id) }
memberList = tempList
sectionedItems.onNext(memberList.mapSection())
}
}
/// MQTT 位置更新后刷新成员的地址、电量、在线状态
func updateMemberLocation(userId: String, lat: Double, lon: Double, address: String, battery: String, isOnline: Bool, lastUpdateText: String) {
guard let idx = memberList.firstIndex(where: { $0.user_id == userId }) else { return }
var updated = memberList
updated[idx].last_position = "\(lat):\(lon):\(address)"
updated[idx].battery = battery
updated[idx].is_online = isOnline
updated[idx].lastUpdateText = lastUpdateText
memberList = updated // 触发 didSet → 排序 + 重发 sectionedItems
}
// MARK: - Init

View File

@ -0,0 +1,214 @@
//
// InteractionView.swift
// QuickLocation
//
// Created by 八条 on 2026/6/15.
//
import UIKit
class InteractionView: UIView {
func configure(member: CircleMember) {
avaterImgView.image = UIImage(named: "UserIcon/\(member.avatar)")
nameLab.text = member.name
locationLab.text = member.address
// 电量
let batteryInt = Int(member.battery) ?? 0
let batteryPercent = min(CGFloat(batteryInt), 100)
batteryView.layoutChain.width(CGFloat(16 - 1) * batteryPercent / 100.0)
batteryLab.text = "\(member.battery)%"
}
private func setupRx() {
}
private func setupUI() {
addSubview(infoView)
infoView.addSubview(headerBgView)
infoView.addSubview(lineView)
infoView.addSubview(avaterImgView)
infoView.addSubview(batteryInfoView)
batteryInfoView.addSubview(cornerView)
cornerView.addSubview(batteryView)
cornerView.addSubview(batteryIcon)
cornerView.addSubview(batteryLab)
infoView.addSubview(nameLab)
infoView.addSubview(locationLab)
infoView.addSubview(navigateBtn)
infoView.addSubview(shareBtn)
infoView.layoutChain.edges()
headerBgView.layoutChain
.edges(excludingEdge: .bottom)
.height(134)
lineView.layoutChain
.top(13)
.width(36)
.height(4)
.centerX()
avaterImgView.layoutChain
.top(25)
.left(25)
.width(50)
.height(50)
batteryInfoView.layoutChain
.leftToView(avaterImgView)
.rightToView(avaterImgView)
.bottomToView(avaterImgView)
.height(12)
cornerView.layoutChain.edges()
batteryIcon.layoutChain
.left(7)
.centerY()
.width(16)
.height(8)
batteryView.layoutChain
.topToView(batteryIcon)
.leftToView(batteryIcon, offset: -1)
.bottomToView(batteryIcon)
batteryLab.layoutChain
.leftToRightOfView(batteryIcon, offset: 4)
.right(5)
.centerY()
nameLab.layoutChain
.topToView(avaterImgView, offset: 8)
.leftToRightOfView(avaterImgView, offset: 15)
locationLab.layoutChain
.topToBottomOfView(nameLab)
.leftToView(nameLab)
shareBtn.layoutChain
.right(15)
.centerY(avaterImgView)
.width(30)
.height(30)
navigateBtn.layoutChain
.rightToLeftOfView(shareBtn, offset: -10)
.centerY(avaterImgView)
.width(30)
.height(30)
}
lazy var infoView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view
}()
lazy var headerBgView: UIImageView = {
let view = UIImageView(image: UIImage(named: "Home/interaction_header"))
return view
}()
lazy var lineView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.cornerRadius = 2
return view
}()
lazy var avaterImgView: UIImageView = {
let view = UIImageView()
view.backgroundColor = .lightGray
view.contentMode = .scaleAspectFill
view.cornerRadius = 25
return view
}()
lazy var batteryInfoView: UIView = {
let view = UIView()
view.backgroundColor = .clear
view.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1).cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 2)
view.layer.shadowOpacity = 1
view.layer.shadowRadius = 6
return view
}()
lazy var cornerView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.cornerRadius = 6
return view
}()
lazy var batteryView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexStr: "#75E582")
return view
}()
lazy var batteryIcon: UIImageView = {
let view = UIImageView()
view.backgroundColor = .clear
view.image = UIImage(named: "Home/battery")
return view
}()
lazy var batteryLab: UILabel = {
let label = UILabel()
label.textColor = UIColor(hexStr: "#D4D4D4")
label.font = .systemFont(ofSize: 6, weight: .medium)
return label
}()
lazy var nameLab: UILabel = {
let label = UILabel()
label.textColor = UIColor(hexStr: "#0F2846")
label.font = .systemFont(ofSize: 14, weight: .semibold)
return label
}()
lazy var locationLab: UILabel = {
let label = UILabel()
label.textColor = UIColor(hexStr: "#8D8D8D")
label.font = .systemFont(ofSize: 10, weight: .regular)
return label
}()
lazy var navigateBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named: "Home/navigate"), for: .normal)
btn.cornerRadius = 15
btn.extendEdgeInsets = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 0)
return btn
}()
lazy var shareBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named: "Home/share"), for: .normal)
btn.cornerRadius = 15
btn.extendEdgeInsets = UIEdgeInsets(top: 30, left: 0, bottom: 30, right: 15)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
setupUI()
setupRx()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
infoView.layoutIfNeeded()
infoView.setCornerRadius(corners: [.topLeft ,.topRight], withCornerRadii: CGSize(width: 20, height: 20))
}
}

View File

@ -0,0 +1,96 @@
//
// QuickMessageView.swift
// QuickLocation
//
// Created by 八条 on 2026/6/15.
//
import UIKit
import TagListView
class QuickMessageView: UIView {
private let list: [String] = [
"爱你哦!", "预计到达时间?", "发生什么情况?", "注意安全", "在路上", "给我打电话",
]
func setupTagData(list: [String]) {
tagListView.removeAllTags()
for text in list {
let tag = TTGTextTag.init()
let content = TTGTextTagStringContent.init(text: text)
content.textColor = ThemeManager.shared.color.titleAuxColor
content.textFont = UIFont.systemFont(ofSize: 12, weight: .medium)
let normalStyle = TTGTextTagStyle.init()
normalStyle.backgroundColor = .white
normalStyle.extraSpace = CGSize.init(width: 15, height: 15)
normalStyle.shadowColor = UIColor(hexStr: "#333333", alpha: 0.25)
normalStyle.borderColor = .clear
normalStyle.cornerRadius = 8
tag.content = content
tag.style = normalStyle
tagListView.addTag(tag)
}
tagListView.reload()
tagListView.setNeedsLayout()
tagListView.layoutIfNeeded()
}
private func setupRx() {
}
private func setupUI() {
addSubview(closeBtn)
addSubview(tagListView)
closeBtn.layoutChain
.top()
.left(23)
.width(40)
.height(40)
tagListView.layoutChain
.topToBottomOfView(closeBtn, offset: 15)
.edgesHorzontal(15)
.height(38)
}
lazy var closeBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named: "Common/x"), for: .normal)
btn.setBackgroundColor(.black.withAlphaComponent(0.5), for: .normal)
btn.cornerRadius = 20
btn.extendEdgeInsets = UIEdgeInsets(top: 50, left: 23, bottom: 0, right: 30)
return btn
}()
lazy var tagListView: TTGTextTagCollectionView = {
let tagsView = TTGTextTagCollectionView.init(frame: .zero)
tagsView.scrollView.scrollsToTop = false
tagsView.scrollView.bounces = false
tagsView.showsVerticalScrollIndicator = false
tagsView.showsHorizontalScrollIndicator = false
tagsView.scrollDirection = .horizontal
tagsView.numberOfLines = 1
tagsView.horizontalSpacing = 10
return tagsView
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
setupUI()
setupRx()
setupTagData(list: list)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

View File

@ -69,6 +69,7 @@ class LaunchViewController: BaseViewController {
func getUserConfig() {
SystemService.userConfig().subscribe(onNext: { response in
guard let model = response.model else { return }
MQTTService.shared.connect()
Defaults[\.loginToken] = model.token
AppContextManager.shared.systemConfig = model.config
self.getUserIMToken()

View File

@ -16,6 +16,7 @@ struct CircleMember {
let address: String
let heading: Double
let lastUpdateText: String
let battery: String
var isCurrentUser: Bool { id == "current" }
}
@ -33,6 +34,7 @@ extension CircleMember {
address = addr
heading = 0
lastUpdateText = member.is_online ? "在线" : "离线"
battery = member.battery
}
/// 解析 last_position:格式 "lat:lng:address"

View File

@ -9,6 +9,9 @@ import MAMapKit
final class MemberAnnotationView: MAAnnotationView {
/// 标注被点击的回调
var onTap: ((MemberAnnotation) -> Void)?
// MARK: - Design Constants
static let avatarOuterSize: CGFloat = 50
static let avatarInnerSize: CGFloat = 48
@ -96,10 +99,18 @@ final class MemberAnnotationView: MAAnnotationView {
// MARK: - Configure
func configure(with member: CircleMember) {
self.isEnabled = true
avatarImageView.image = UIImage(named: "UserIcon/\(member.avatar)")
avatarImageView.backgroundColor = member.avatar.isEmpty ? .lightGray : .clear
nameLabel.text = member.name
isCurrentUser = member.isCurrentUser
canShowCallout = false
// 非当前用户标注可点击弹出面板
if !member.isCurrentUser && gestureRecognizers?.isEmpty ?? true {
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
addGestureRecognizer(tap)
}
if member.isCurrentUser {
configureAsCurrentUser(heading: member.heading)
@ -108,22 +119,29 @@ final class MemberAnnotationView: MAAnnotationView {
}
}
@objc private func handleTap() {
guard let ann = annotation as? MemberAnnotation else { return }
onTap?(ann)
}
private func configureAsCurrentUser(heading: Double) {
nameTagView.isHidden = true
stopPulseAnimation()
let size = Self.radarSize
let outer = Self.avatarOuterSize
let padding: CGFloat = 30
let size = outer + padding * 2
bounds = CGRect(x: 0, y: 0, width: size, height: size)
centerOffset = .zero
containerView.frame = bounds
let avatarX = (size - Self.avatarOuterSize) / 2
let avatarY = (size - Self.avatarOuterSize) / 2
let avatarX = (size - outer) / 2
let avatarY = (size - outer) / 2
avatarOuterCircle.frame = CGRect(x: avatarX, y: avatarY,
width: Self.avatarOuterSize, height: Self.avatarOuterSize)
width: outer, height: outer)
avatarImageView.frame = CGRect(
x: (Self.avatarOuterSize - Self.avatarInnerSize) / 2,
y: (Self.avatarOuterSize - Self.avatarInnerSize) / 2,
x: (outer - Self.avatarInnerSize) / 2,
y: (outer - Self.avatarInnerSize) / 2,
width: Self.avatarInnerSize, height: Self.avatarInnerSize
)

View File

@ -0,0 +1,19 @@
//
// TTGTagCollectionView-Bridging-Header.h
// TTGTagCollectionView
//
// Created by zekunyan on 2021/4/21.
//
#ifndef TTGTagCollectionView_Bridging_Header_h
#define TTGTagCollectionView_Bridging_Header_h
#import "TTGTagCollectionView.h"
#import "TTGTextTagCollectionView.h"
#import "TTGTextTag.h"
#import "TTGTextTagContent.h"
#import "TTGTextTagStringContent.h"
#import "TTGTextTagAttributedStringContent.h"
#import "TTGTextTagStyle.h"
#endif /* TTGTagCollectionView_Bridging_Header_h */

View File

@ -0,0 +1,112 @@
//
// TTGTagCollectionView.h
// Pods
//
// Created by zekunyan on 15/12/26.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import <UIKit/UIKit.h>
@class TTGTagCollectionView;
/**
* Tags scroll direction
*/
typedef NS_ENUM(NSInteger, TTGTagCollectionScrollDirection) {
TTGTagCollectionScrollDirectionVertical = 0, // Default
TTGTagCollectionScrollDirectionHorizontal = 1
};
/**
* Tags alignment
*/
typedef NS_ENUM(NSInteger, TTGTagCollectionAlignment) {
TTGTagCollectionAlignmentLeft = 0, // Default
TTGTagCollectionAlignmentCenter, // Center
TTGTagCollectionAlignmentRight, // Right
TTGTagCollectionAlignmentFillByExpandingSpace, // Expand horizontal spacing and fill
TTGTagCollectionAlignmentFillByExpandingWidth, // Expand width and fill
TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine // Expand width and fill, except last line
};
/**
* Tags delegate
*/
@protocol TTGTagCollectionViewDelegate <NSObject>
@required
- (CGSize)tagCollectionView:(TTGTagCollectionView *)tagCollectionView sizeForTagAtIndex:(NSUInteger)index;
@optional
- (BOOL)tagCollectionView:(TTGTagCollectionView *)tagCollectionView shouldSelectTag:(UIView *)tagView atIndex:(NSUInteger)index;
- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView didSelectTag:(UIView *)tagView atIndex:(NSUInteger)index;
- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView updateContentSize:(CGSize)contentSize;
@end
/**
* Tags dataSource
*/
@protocol TTGTagCollectionViewDataSource <NSObject>
@required
- (NSUInteger)numberOfTagsInTagCollectionView:(TTGTagCollectionView *)tagCollectionView;
- (UIView *)tagCollectionView:(TTGTagCollectionView *)tagCollectionView tagViewForIndex:(NSUInteger)index;
@end
@interface TTGTagCollectionView : UIView
@property (nonatomic, weak) id <TTGTagCollectionViewDataSource> dataSource;
@property (nonatomic, weak) id <TTGTagCollectionViewDelegate> delegate;
// Inside scrollView
@property (nonatomic, strong, readonly) UIScrollView *scrollView;
// Tags scroll direction, default is vertical.
@property (nonatomic, assign) TTGTagCollectionScrollDirection scrollDirection;
// Tags layout alignment, default is left.
@property (nonatomic, assign) TTGTagCollectionAlignment alignment;
// Number of lines. 0 means no limit, default is 0 for vertical and 1 for horizontal.
@property (nonatomic, assign) NSUInteger numberOfLines;
// The real number of lines ignoring the numberOfLines value
@property (nonatomic, assign, readonly) NSUInteger actualNumberOfLines;
// Horizontal and vertical space between tags, default is 4.
@property (nonatomic, assign) CGFloat horizontalSpacing;
@property (nonatomic, assign) CGFloat verticalSpacing;
// Content inset, default is UIEdgeInsetsMake(2, 2, 2, 2).
@property (nonatomic, assign) UIEdgeInsets contentInset;
// The true tags content size, readonly
@property (nonatomic, assign, readonly) CGSize contentSize;
// Manual content height
// Default = NO, set will update content
@property (nonatomic, assign) BOOL manualCalculateHeight;
// Default = 0, set will update content
@property (nonatomic, assign) CGFloat preferredMaxLayoutWidth;
// Scroll indicator
@property (nonatomic, assign) BOOL showsHorizontalScrollIndicator;
@property (nonatomic, assign) BOOL showsVerticalScrollIndicator;
// Tap blank area callback
@property (nonatomic, copy) void (^onTapBlankArea)(CGPoint location);
// Tap all area callback
@property (nonatomic, copy) void (^onTapAllArea)(CGPoint location);
/**
* Reload all tag cells
*/
- (void)reload;
/**
* Returns the index of the tag located at the specified point.
* If item at point is not found, returns NSNotFound.
*/
- (NSInteger)indexOfTagAt:(CGPoint)point;
@end

View File

@ -0,0 +1,490 @@
//
// TTGTagCollectionView.m
// Pods
//
// Created by zekunyan on 15/12/26.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTagCollectionView.h"
@interface TTGTagCollectionView ()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, assign) BOOL needsLayoutTagViews;
@property (nonatomic, assign) NSUInteger actualNumberOfLines;
@end
@implementation TTGTagCollectionView
#pragma mark - Init
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self commonInit];
}
return self;
}
- (void)commonInit {
if (_scrollView) {
return;
}
_horizontalSpacing = 4;
_verticalSpacing = 4;
_contentInset = UIEdgeInsetsMake(2, 2, 2, 2);
_scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
_scrollView.backgroundColor = [UIColor clearColor];
_scrollView.userInteractionEnabled = YES;
[self addSubview:_scrollView];
_containerView = [[UIView alloc] initWithFrame:_scrollView.bounds];
_containerView.backgroundColor = [UIColor clearColor];
_containerView.userInteractionEnabled = YES;
[_scrollView addSubview:_containerView];
UITapGestureRecognizer *tapGesture = [UITapGestureRecognizer new];
[tapGesture addTarget:self action:@selector(onTapGesture:)];
[_containerView addGestureRecognizer:tapGesture];
[self setNeedsLayoutTagViews];
}
#pragma mark - Public methods
- (void)reload {
if (![self isDelegateAndDataSourceValid]) {
return;
}
// Remove all tag views
[_containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
// Add tag view
for (NSUInteger i = 0; i < [_dataSource numberOfTagsInTagCollectionView:self]; i++) {
[_containerView addSubview:[_dataSource tagCollectionView:self tagViewForIndex:i]];
}
// Update tag view frame
[self setNeedsLayoutTagViews];
[self layoutTagViews];
}
- (NSInteger)indexOfTagAt:(CGPoint)point {
// We expect the point to be a point wrt to the TTGTagCollectionView.
// so convert this point first to a point wrt to the container view.
CGPoint convertedPoint = [self convertPoint:point toView:_containerView];
for (NSUInteger i = 0; i < [self.dataSource numberOfTagsInTagCollectionView:self]; i++) {
UIView *tagView = [self.dataSource tagCollectionView:self tagViewForIndex:i];
if (CGRectContainsPoint(tagView.frame, convertedPoint) && !tagView.isHidden) {
return i;
}
}
return NSNotFound;
}
#pragma mark - Gesture
- (void)onTapGesture:(UITapGestureRecognizer *)tapGesture {
CGPoint tapPointInCollectionView = [tapGesture locationInView:self];
if (![self.dataSource respondsToSelector:@selector(numberOfTagsInTagCollectionView:)] ||
![self.dataSource respondsToSelector:@selector(tagCollectionView:tagViewForIndex:)] ||
![self.delegate respondsToSelector:@selector(tagCollectionView:didSelectTag:atIndex:)]) {
if (_onTapBlankArea) {
_onTapBlankArea(tapPointInCollectionView);
}
if (_onTapAllArea) {
_onTapAllArea(tapPointInCollectionView);
}
return;
}
CGPoint tapPointInScrollView = [tapGesture locationInView:_containerView];
BOOL hasLocatedToTag = NO;
for (NSUInteger i = 0; i < [self.dataSource numberOfTagsInTagCollectionView:self]; i++) {
UIView *tagView = [self.dataSource tagCollectionView:self tagViewForIndex:i];
if (CGRectContainsPoint(tagView.frame, tapPointInScrollView) && !tagView.isHidden) {
hasLocatedToTag = YES;
if ([self.delegate respondsToSelector:@selector(tagCollectionView:shouldSelectTag:atIndex:)]) {
if ([self.delegate tagCollectionView:self shouldSelectTag:tagView atIndex:i]) {
[self.delegate tagCollectionView:self didSelectTag:tagView atIndex:i];
}
} else {
[self.delegate tagCollectionView:self didSelectTag:tagView atIndex:i];
}
}
}
if (!hasLocatedToTag) {
if (_onTapBlankArea) {
_onTapBlankArea(tapPointInCollectionView);
}
}
if (_onTapAllArea) {
_onTapAllArea(tapPointInCollectionView);
}
}
#pragma mark - Override
- (void)layoutSubviews {
[super layoutSubviews];
if (!CGRectEqualToRect(_scrollView.frame, self.bounds)) {
_scrollView.frame = self.bounds;
[self setNeedsLayoutTagViews];
[self layoutTagViews];
_containerView.frame = (CGRect){CGPointZero, _scrollView.contentSize};
}
[self layoutTagViews];
}
- (CGSize)intrinsicContentSize {
return _scrollView.contentSize;
}
- (CGSize)sizeThatFits:(CGSize)size {
return self.contentSize;
}
#pragma mark - Layout
- (void)layoutTagViews {
if (!_needsLayoutTagViews || ![self isDelegateAndDataSourceValid]) {
return;
}
if (_scrollDirection == TTGTagCollectionScrollDirectionVertical) {
[self layoutTagViewsForVerticalDirection];
} else {
[self layoutTagViewsForHorizontalDirection];
}
_needsLayoutTagViews = NO;
[self invalidateIntrinsicContentSize];
}
- (void)layoutTagViewsForVerticalDirection {
NSUInteger count = [_dataSource numberOfTagsInTagCollectionView:self];
NSUInteger currentLineTagsCount = 0;
CGFloat totalWidth = (_manualCalculateHeight && _preferredMaxLayoutWidth > 0) ? _preferredMaxLayoutWidth : CGRectGetWidth(self.bounds);
CGFloat maxLineWidth = totalWidth - _contentInset.left - _contentInset.right;
CGFloat currentLineX = 0;
CGFloat currentLineMaxHeight = 0;
NSMutableArray <NSNumber *> *eachLineMaxHeightNumbers = [NSMutableArray new];
NSMutableArray <NSNumber *> *eachLineWidthNumbers = [NSMutableArray new];
NSMutableArray <NSNumber *> *eachLineTagCountNumbers = [NSMutableArray new];
NSMutableArray <NSArray <NSNumber *> *> *eachLineTagIndexs = [NSMutableArray new];
NSMutableArray <NSNumber *> *tmpTagIndexNumbers = [NSMutableArray new];
// Get each line max height ,width and tag count
for (NSUInteger i = 0; i < count; i++) {
CGSize tagSize = [_delegate tagCollectionView:self sizeForTagAtIndex:i];
if (currentLineX + tagSize.width > maxLineWidth && tmpTagIndexNumbers.count > 0) {
// New Line
[eachLineMaxHeightNumbers addObject:@(currentLineMaxHeight)];
[eachLineWidthNumbers addObject:@(currentLineX - _horizontalSpacing)];
[eachLineTagCountNumbers addObject:@(currentLineTagsCount)];
[eachLineTagIndexs addObject:tmpTagIndexNumbers];
tmpTagIndexNumbers = [NSMutableArray new];
currentLineTagsCount = 0;
currentLineMaxHeight = 0;
currentLineX = 0;
}
// Line limit
if (_numberOfLines != 0) {
UIView *tagView = [_dataSource tagCollectionView:self tagViewForIndex:i];
tagView.hidden = eachLineWidthNumbers.count >= _numberOfLines;
}
currentLineX += tagSize.width + _horizontalSpacing;
currentLineTagsCount += 1;
currentLineMaxHeight = MAX(tagSize.height, currentLineMaxHeight);
[tmpTagIndexNumbers addObject:@(i)];
}
// Add last
[eachLineMaxHeightNumbers addObject:@(currentLineMaxHeight)];
[eachLineWidthNumbers addObject:@(currentLineX - _horizontalSpacing)];
[eachLineTagCountNumbers addObject:@(currentLineTagsCount)];
[eachLineTagIndexs addObject:tmpTagIndexNumbers];
// Actual number of lines
_actualNumberOfLines = eachLineTagCountNumbers.count;
// Line limit
if (_numberOfLines != 0) {
eachLineMaxHeightNumbers = [[eachLineMaxHeightNumbers subarrayWithRange:NSMakeRange(0, MIN(eachLineMaxHeightNumbers.count, _numberOfLines))] mutableCopy];
eachLineWidthNumbers = [[eachLineWidthNumbers subarrayWithRange:NSMakeRange(0, MIN(eachLineWidthNumbers.count, _numberOfLines))] mutableCopy];
eachLineTagCountNumbers = [[eachLineTagCountNumbers subarrayWithRange:NSMakeRange(0, MIN(eachLineTagCountNumbers.count, _numberOfLines))] mutableCopy];
eachLineTagIndexs = [[eachLineTagIndexs subarrayWithRange:NSMakeRange(0, MIN(eachLineTagIndexs.count, _numberOfLines))] mutableCopy];
}
// Prepare
[self layoutEachLineTagsWithMaxLineWidth:maxLineWidth
numberOfLines:eachLineTagCountNumbers.count
eachLineTagIndexs:eachLineTagIndexs
eachLineTagCount:eachLineTagCountNumbers
eachLineWidth:eachLineWidthNumbers
eachLineMaxHeight:eachLineMaxHeightNumbers];
}
- (void)layoutTagViewsForHorizontalDirection {
NSInteger count = [_dataSource numberOfTagsInTagCollectionView:self];
_numberOfLines = _numberOfLines == 0 ? 1 : _numberOfLines;
CGFloat maxLineWidth = 0;
NSMutableArray <NSNumber *> *eachLineMaxHeightNumbers = [NSMutableArray new];
NSMutableArray <NSNumber *> *eachLineWidthNumbers = [NSMutableArray new];
NSMutableArray <NSNumber *> *eachLineTagCountNumbers = [NSMutableArray new];
NSMutableArray <NSMutableArray <NSNumber *> *> *eachLineTagIndexs = [NSMutableArray new];
// Init each line
for (NSInteger currentLine = 0; currentLine < _numberOfLines; currentLine++) {
[eachLineMaxHeightNumbers addObject:@0];
[eachLineWidthNumbers addObject:@0];
[eachLineTagCountNumbers addObject:@0];
[eachLineTagIndexs addObject:[NSMutableArray new]];
}
// Add tags
for (NSUInteger tagIndex = 0; tagIndex < count; tagIndex++) {
NSUInteger currentLine = tagIndex % _numberOfLines;
NSUInteger currentLineTagsCount = eachLineTagCountNumbers[currentLine].unsignedIntegerValue;
CGFloat currentLineMaxHeight = eachLineMaxHeightNumbers[currentLine].floatValue;
CGFloat currentLineX = eachLineWidthNumbers[currentLine].floatValue;
NSMutableArray *currentLineTagIndexNumbers = eachLineTagIndexs[currentLine];
CGSize tagSize = [_delegate tagCollectionView:self sizeForTagAtIndex:tagIndex];
currentLineX += tagSize.width + _horizontalSpacing;
currentLineMaxHeight = MAX(tagSize.height, currentLineMaxHeight);
currentLineTagsCount += 1;
[currentLineTagIndexNumbers addObject:@(tagIndex)];
eachLineTagCountNumbers[currentLine] = @(currentLineTagsCount);
eachLineMaxHeightNumbers[currentLine] = @(currentLineMaxHeight);
eachLineWidthNumbers[currentLine] = @(currentLineX);
eachLineTagIndexs[currentLine] = currentLineTagIndexNumbers;
}
// Remove extra space
for (NSInteger currentLine = 0; currentLine < _numberOfLines; currentLine++) {
CGFloat currentLineWidth = eachLineWidthNumbers[currentLine].floatValue;
currentLineWidth -= _horizontalSpacing;
eachLineWidthNumbers[currentLine] = @(currentLineWidth);
maxLineWidth = MAX(currentLineWidth, maxLineWidth);
}
// Prepare
[self layoutEachLineTagsWithMaxLineWidth:maxLineWidth
numberOfLines:eachLineTagCountNumbers.count
eachLineTagIndexs:eachLineTagIndexs
eachLineTagCount:eachLineTagCountNumbers
eachLineWidth:eachLineWidthNumbers
eachLineMaxHeight:eachLineMaxHeightNumbers];
}
- (void)layoutEachLineTagsWithMaxLineWidth:(CGFloat)maxLineWidth
numberOfLines:(NSUInteger)numberOfLines
eachLineTagIndexs:(NSArray <NSArray <NSNumber *> *> *)eachLineTagIndexs
eachLineTagCount:(NSArray <NSNumber *> *)eachLineTagCount
eachLineWidth:(NSArray <NSNumber *> *)eachLineWidth
eachLineMaxHeight:(NSArray <NSNumber *> *)eachLineMaxHeight {
CGFloat currentYBase = _contentInset.top;
for (NSUInteger currentLine = 0; currentLine < numberOfLines; currentLine++) {
CGFloat currentLineMaxHeight = eachLineMaxHeight[currentLine].floatValue;
CGFloat currentLineWidth = eachLineWidth[currentLine].floatValue;
CGFloat currentLineTagsCount = eachLineTagCount[currentLine].unsignedIntegerValue;
// Alignment x offset
CGFloat currentLineXOffset = 0;
CGFloat currentLineAdditionWidth = 0;
CGFloat acturalHorizontalSpacing = _horizontalSpacing;
__block CGFloat currentLineX = 0;
switch (_alignment) {
case TTGTagCollectionAlignmentLeft:
currentLineXOffset = _contentInset.left;
break;
case TTGTagCollectionAlignmentCenter:
currentLineXOffset = (maxLineWidth - currentLineWidth) / 2 + _contentInset.left;
break;
case TTGTagCollectionAlignmentRight:
currentLineXOffset = maxLineWidth - currentLineWidth + _contentInset.left;
break;
case TTGTagCollectionAlignmentFillByExpandingSpace:
currentLineXOffset = _contentInset.left;
acturalHorizontalSpacing = _horizontalSpacing +
(maxLineWidth - currentLineWidth) / (CGFloat)(currentLineTagsCount - 1);
currentLineWidth = maxLineWidth;
break;
case TTGTagCollectionAlignmentFillByExpandingWidth:
case TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine:
currentLineXOffset = _contentInset.left;
currentLineAdditionWidth = (maxLineWidth - currentLineWidth) / (CGFloat)currentLineTagsCount;
currentLineWidth = maxLineWidth;
if (_alignment == TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine &&
currentLine == numberOfLines - 1 &&
numberOfLines != 1) {
// Reset last line width for TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine
currentLineAdditionWidth = 0;
}
break;
}
// Current line
[eachLineTagIndexs[currentLine] enumerateObjectsUsingBlock:^(NSNumber * _Nonnull tagIndexNumber, NSUInteger idx, BOOL * _Nonnull stop) {
NSUInteger tagIndex = tagIndexNumber.unsignedIntegerValue;
UIView *tagView = [self.dataSource tagCollectionView:self tagViewForIndex:tagIndex];
CGSize tagSize = [self.delegate tagCollectionView:self sizeForTagAtIndex:tagIndex];
CGPoint origin;
origin.x = currentLineXOffset + currentLineX;
origin.y = currentYBase + (currentLineMaxHeight - tagSize.height) / 2;
tagSize.width += currentLineAdditionWidth;
if (self.scrollDirection == TTGTagCollectionScrollDirectionVertical && tagSize.width > maxLineWidth) {
tagSize.width = maxLineWidth;
}
tagView.hidden = NO;
tagView.frame = (CGRect){origin, tagSize};
currentLineX += tagSize.width + acturalHorizontalSpacing;
}];
// Next line
currentYBase += currentLineMaxHeight + _verticalSpacing;
}
// Content size
maxLineWidth += _contentInset.right + _contentInset.left;
CGSize contentSize = CGSizeMake(maxLineWidth, currentYBase - _verticalSpacing + _contentInset.bottom);
if (!CGSizeEqualToSize(contentSize, _scrollView.contentSize)) {
_scrollView.contentSize = contentSize;
_containerView.frame = (CGRect){CGPointZero, contentSize};
if ([self.delegate respondsToSelector:@selector(tagCollectionView:updateContentSize:)]) {
[self.delegate tagCollectionView:self updateContentSize:contentSize];
}
}
}
- (void)setNeedsLayoutTagViews {
_needsLayoutTagViews = YES;
}
#pragma mark - Check delegate and dataSource
- (BOOL)isDelegateAndDataSourceValid {
BOOL isValid = _delegate != nil && _dataSource != nil;
isValid = isValid && [_delegate respondsToSelector:@selector(tagCollectionView:sizeForTagAtIndex:)];
isValid = isValid && [_dataSource respondsToSelector:@selector(tagCollectionView:tagViewForIndex:)];
isValid = isValid && [_dataSource respondsToSelector:@selector(numberOfTagsInTagCollectionView:)];
return isValid;
}
#pragma mark - Setter Getter
- (UIScrollView *)scrollView {
return _scrollView;
}
- (void)setScrollDirection:(TTGTagCollectionScrollDirection)scrollDirection {
_scrollDirection = scrollDirection;
[self setNeedsLayoutTagViews];
}
- (void)setAlignment:(TTGTagCollectionAlignment)alignment {
_alignment = alignment;
[self setNeedsLayoutTagViews];
}
- (void)setNumberOfLines:(NSUInteger)numberOfLines {
_numberOfLines = numberOfLines;
[self setNeedsLayoutTagViews];
}
- (NSUInteger)actualNumberOfLines {
if (_scrollDirection == TTGTagCollectionScrollDirectionHorizontal) {
return _numberOfLines;
} else {
return _actualNumberOfLines;
}
}
- (void)setHorizontalSpacing:(CGFloat)horizontalSpacing {
_horizontalSpacing = horizontalSpacing;
[self setNeedsLayoutTagViews];
}
- (void)setVerticalSpacing:(CGFloat)verticalSpacing {
_verticalSpacing = verticalSpacing;
[self setNeedsLayoutTagViews];
}
- (void)setContentInset:(UIEdgeInsets)contentInset {
_contentInset = contentInset;
[self setNeedsLayoutTagViews];
}
- (CGSize)contentSize {
[self layoutTagViews];
return _scrollView.contentSize;
}
- (void)setManualCalculateHeight:(BOOL)manualCalculateHeight {
_manualCalculateHeight = manualCalculateHeight;
[self setNeedsLayoutTagViews];
}
- (void)setPreferredMaxLayoutWidth:(CGFloat)preferredMaxLayoutWidth {
_preferredMaxLayoutWidth = preferredMaxLayoutWidth;
[self setNeedsLayoutTagViews];
}
- (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator {
_scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
}
- (BOOL)showsHorizontalScrollIndicator {
return _scrollView.showsHorizontalScrollIndicator;
}
- (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator {
_scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
}
- (BOOL)showsVerticalScrollIndicator {
return _scrollView.showsVerticalScrollIndicator;
}
@end

View File

@ -0,0 +1,106 @@
//
// TTGTextTag.h
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "TTGTextTagStyle.h"
#import "TTGTextTagContent.h"
@interface TTGTextTag : NSObject <NSCopying>
/// ID
@property (nonatomic, assign, readonly) NSUInteger tagId; // Auto increase. The only identifier and main key for a tag
/// Attachment object. You can use this to bind any object you want to each tag.
@property (nonatomic, strong) id _Nullable attachment;
/// Normal state content and style
@property (nonatomic, copy) TTGTextTagContent * _Nonnull content;
@property (nonatomic, copy) TTGTextTagStyle * _Nonnull style;
/// Selected state content and style
@property (nonatomic, copy) TTGTextTagContent * _Nullable selectedContent;
@property (nonatomic, copy) TTGTextTagStyle * _Nullable selectedStyle;
/// Selection state
@property (nonatomic, assign) BOOL selected;
/// Init
/**
Init with single content and style
@param content content for both normal and selection state.
@param style style for both normal and selection state.
@return instance
*/
- (instancetype _Nonnull)initWithContent:(TTGTextTagContent *_Nonnull)content
style:(TTGTextTagStyle *_Nonnull)style;
/**
Init with different content and style
@param content content for normal state
@param style style for normal state
@param selectedContent content for selection state
@param selectedStyle style for selection state
@return instance
*/
- (instancetype _Nonnull)initWithContent:(TTGTextTagContent *_Nonnull)content
style:(TTGTextTagStyle *_Nonnull)style
selectedContent:(TTGTextTagContent *_Nullable)selectedContent
selectedStyle:(TTGTextTagStyle *_Nullable)selectedStyle;
/**
Tag with single content and style
@param content content for both normal and selection state.
@param style style for both normal and selection state.
@return instance
*/
+ (instancetype _Nonnull)tagWithContent:(TTGTextTagContent *_Nonnull)content
style:(TTGTextTagStyle *_Nonnull)style;
/**
Tag with different content and style
@param content content for normal state
@param style style for normal state
@param selectedContent content for selection state
@param selectedStyle style for selection state
@return instance
*/
+ (instancetype _Nonnull)tagWithContent:(TTGTextTagContent *_Nonnull)content
style:(TTGTextTagStyle *_Nonnull)style
selectedContent:(TTGTextTagContent *_Nullable)selectedContent
selectedStyle:(TTGTextTagStyle *_Nullable)selectedStyle;
/**
Get current state rightful content
@return content
*/
- (TTGTextTagContent *_Nonnull)getRightfulContent;
/**
Get current state rightful style
@return style
*/
- (TTGTextTagStyle *_Nonnull)getRightfulStyle;
/// Base system methods
- (BOOL)isEqual:(id _Nullable)other;
- (BOOL)isEqualToTag:(TTGTextTag *_Nullable)tag;
- (NSUInteger)hash;
/// Copy
- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone;
@end

View File

@ -0,0 +1,123 @@
//
// TTGTextTag.m
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTag.h"
#import "TTGTextTagStringContent.h"
static NSUInteger TTGTextTagAutoIncreasedId = 0;
@implementation TTGTextTag
- (instancetype)initWithContent:(TTGTextTagContent *)content
style:(TTGTextTagStyle *)style {
self = [self init];
if (self) {
self.content = content;
self.style = style;
}
return self;
}
- (instancetype)initWithContent:(TTGTextTagContent *)content
style:(TTGTextTagStyle *)style
selectedContent:(TTGTextTagContent *)selectedContent
selectedStyle:(TTGTextTagStyle *)selectedStyle {
self = [self init];
if (self) {
self.content = content;
self.style = style;
self.selectedContent = selectedContent;
self.selectedStyle = selectedStyle;
}
return self;
}
+ (instancetype)tagWithContent:(TTGTextTagContent *)content
style:(TTGTextTagStyle *)style {
return [[self alloc] initWithContent:content style:style];
}
+ (instancetype)tagWithContent:(TTGTextTagContent *)content
style:(TTGTextTagStyle *)style
selectedContent:(TTGTextTagContent *)selectedContent
selectedStyle:(TTGTextTagStyle *)selectedStyle {
return [[self alloc] initWithContent:content
style:style
selectedContent:selectedContent
selectedStyle:selectedStyle];
}
- (instancetype)init {
self = [super init];
if (self) {
_tagId = TTGTextTagAutoIncreasedId++;
_attachment = nil;
}
return self;
}
- (TTGTextTagContent *)selectedContent {
if (_selectedContent == nil) {
_selectedContent = [_content copy];
}
return _selectedContent;
}
- (TTGTextTagStyle *)selectedStyle {
if (_selectedStyle == nil) {
_selectedStyle = [_style copy];
}
return _selectedStyle;
}
- (TTGTextTagContent *)getRightfulContent {
return _selected ? self.selectedContent : self.content;
}
- (TTGTextTagStyle *)getRightfulStyle {
return _selected ? self.selectedStyle : self.style;
}
- (BOOL)isEqual:(id)other {
if (other == self)
return YES;
if (!other || ![[other class] isEqual:[self class]])
return NO;
return [self isEqualToTag:other];
}
- (BOOL)isEqualToTag:(TTGTextTag *)tag {
if (self == tag)
return YES;
if (tag == nil)
return NO;
if (self.tagId != tag.tagId)
return NO;
return YES;
}
- (NSUInteger)hash {
return (NSUInteger)self.tagId;
}
- (id)copyWithZone:(nullable NSZone *)zone {
TTGTextTag *copy = (TTGTextTag *)[[[self class] allocWithZone:zone] init];
if (copy != nil) {
copy->_tagId = TTGTextTagAutoIncreasedId++;
copy.attachment = self.attachment;
copy.content = self.content;
copy.style = self.style;
copy.selected = self.selected;
copy.selectedContent = self.selectedContent;
copy.selectedStyle = self.selectedStyle;
}
return copy;
}
@end

View File

@ -0,0 +1,29 @@
//
// TTGTextTagAttributedStringContent.h
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTagContent.h"
/**
Rich text content for tag
*/
@interface TTGTextTagAttributedStringContent : TTGTextTagContent
/// Attributed text
@property (nonatomic, copy) NSAttributedString * _Nonnull attributedText;
/// Init with rich text
- (instancetype _Nonnull)initWithAttributedText:(NSAttributedString *_Nonnull)attributedText;
/// Content with rich text
+ (instancetype _Nonnull)contentWithAttributedText:(NSAttributedString *_Nonnull)attributedText;
/// Base system methods
- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone;
- (NSString *_Nonnull)description;
@end

View File

@ -0,0 +1,48 @@
//
// TTGTextTagAttributedStringContent.m
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTagAttributedStringContent.h"
@implementation TTGTextTagAttributedStringContent
- (instancetype)initWithAttributedText:(NSAttributedString *)attributedText {
self = [super init];
if (self) {
self.attributedText = attributedText;
}
return self;
}
+ (instancetype)contentWithAttributedText:(NSAttributedString *)attributedText {
return [[self alloc] initWithAttributedText:attributedText];
}
- (NSAttributedString *)getContentAttributedString {
return self.attributedText;
}
- (NSAttributedString *)attributedText {
return _attributedText ?: [NSAttributedString new];
}
- (id)copyWithZone:(NSZone *)zone {
TTGTextTagAttributedStringContent *copy = (TTGTextTagAttributedStringContent *)[super copyWithZone:zone];
if (copy != nil) {
copy.attributedText = self.attributedText;
}
return copy;
}
- (NSString *)description {
NSMutableString *description = [NSMutableString stringWithFormat:@"<%@: ", NSStringFromClass([self class])];
[description appendFormat:@"self.attributedText=%@", self.attributedText];
[description appendString:@">"];
return description;
}
@end

View File

@ -0,0 +1,124 @@
//
// TTGTextTagCollectionView.h
// Pods
//
// Created by zekunyan on 15/12/26.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TTGTagCollectionView.h"
#import "TTGTextTag.h"
#import "TTGTextTagStringContent.h"
#import "TTGTextTagAttributedStringContent.h"
/**
Highly useful for text tag display.
*/
@class TTGTextTagCollectionView;
/// Delegate
@protocol TTGTextTagCollectionViewDelegate <NSObject>
@optional
- (BOOL)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView
canTapTag:(TTGTextTag *)tag
atIndex:(NSUInteger)index;
- (void)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView
didTapTag:(TTGTextTag *)tag
atIndex:(NSUInteger)index;
- (void)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView
updateContentSize:(CGSize)contentSize;
@end
/// Main Class
@interface TTGTextTagCollectionView : UIView
/// Delegate
@property (weak, nonatomic) id <TTGTextTagCollectionViewDelegate> delegate;
/// Inside scrollView
@property (nonatomic, strong, readonly) UIScrollView *scrollView;
/// Define if the tag can be selected.
@property (assign, nonatomic) BOOL enableTagSelection;
/// Tags scroll direction, default is vertical.
@property (nonatomic, assign) TTGTagCollectionScrollDirection scrollDirection;
/// Tags layout alignment, default is left.
@property (nonatomic, assign) TTGTagCollectionAlignment alignment;
/// Number of lines. 0 means no limit, default is 0 for vertical and 1 for horizontal.
@property (nonatomic, assign) NSUInteger numberOfLines;
/// The real number of lines ignoring the numberOfLines value
@property (nonatomic, assign, readonly) NSUInteger actualNumberOfLines;
/// Tag selection limit, default is 0, means no limit
@property (nonatomic, assign) NSUInteger selectionLimit;
/// Horizontal and vertical space between tags, default is 4.
@property (assign, nonatomic) CGFloat horizontalSpacing;
@property (assign, nonatomic) CGFloat verticalSpacing;
/// Content inset, like padding, default is UIEdgeInsetsMake(2, 2, 2, 2).
@property (nonatomic, assign) UIEdgeInsets contentInset;
/// The true tags content size, readonly
@property (nonatomic, assign, readonly) CGSize contentSize;
/// Manual content height
/// Default = NO, set will update content
@property (nonatomic, assign) BOOL manualCalculateHeight;
/// Default = 0, set will update content
@property (nonatomic, assign) CGFloat preferredMaxLayoutWidth;
/// Scroll indicator
@property (nonatomic, assign) BOOL showsHorizontalScrollIndicator;
@property (nonatomic, assign) BOOL showsVerticalScrollIndicator;
/// Tap blank area callback
@property (nonatomic, copy) void (^onTapBlankArea)(CGPoint location);
/// Tap all area callback
@property (nonatomic, copy) void (^onTapAllArea)(CGPoint location);
/// Reload
- (void)reload;
/// Add
- (void)addTag:(TTGTextTag *)tag;
- (void)addTags:(NSArray <TTGTextTag *> *)tags;
/// Insert
- (void)insertTag:(TTGTextTag *)tag atIndex:(NSUInteger)index;
- (void)insertTags:(NSArray <TTGTextTag *> *)tags atIndex:(NSUInteger)index;
/// Update
- (void)updateTagAtIndex:(NSUInteger)index selected:(BOOL)selected;
- (void)updateTagAtIndex:(NSUInteger)index withNewTag:(TTGTextTag *)tag;
/// Remove
- (void)removeTag:(TTGTextTag *)tag;
- (void)removeTagById:(NSUInteger)tagId;
- (void)removeTagAtIndex:(NSUInteger)index;
- (void)removeAllTags;
/// Get tag
- (TTGTextTag *)getTagAtIndex:(NSUInteger)index;
- (NSArray <TTGTextTag *> *)getTagsInRange:(NSRange)range;
/// Get all
- (NSArray <TTGTextTag *> *)allTags;
- (NSArray <TTGTextTag *> *)allSelectedTags;
- (NSArray <TTGTextTag *> *)allNotSelectedTags;
/**
* Returns the index of the tag located at the specified point.
* If item at point is not found, returns NSNotFound.
*/
- (NSInteger)indexOfTagAtPoint:(CGPoint)point;
@end

View File

@ -0,0 +1,639 @@
//
// TTGTextTagCollectionView.m
// Pods
//
// Created by zekunyan on 15/12/26.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTagCollectionView.h"
#pragma mark - TTGTextTagGradientLabel
@interface TTGTextTagGradientLabel : UILabel
@end
@implementation TTGTextTagGradientLabel
+ (Class)layerClass {
return [CAGradientLayer class];
}
@end
#pragma mark - TTGTextTagLabel
@interface TTGTextTagComponentView : UIView
@property (nonatomic, strong) TTGTextTag *config;
@property (nonatomic, strong) TTGTextTagGradientLabel *label;
@property (nonatomic, strong) CAShapeLayer *borderLayer;
- (BOOL)isEqual:(id)other;
- (BOOL)isEqualToComponentView:(TTGTextTagComponentView *)label;
- (NSUInteger)hash;
@end
@implementation TTGTextTagComponentView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
- (void)commonInit {
_label = [[TTGTextTagGradientLabel alloc] initWithFrame:self.bounds];
_label.textAlignment = NSTextAlignmentCenter;
_label.userInteractionEnabled = YES;
[self addSubview:_label];
}
#pragma mark - Layout
- (void)layoutSubviews {
[super layoutSubviews];
// Update frame
_label.frame = self.bounds;
// Get new path
UIBezierPath *path = [self getNewPath];
// Mask
[self updateMaskWithPath:path];
// Border
[self updateBorderWithPath:path];
// Shadow
[self updateShadowWithPath:path];
}
#pragma mark - intrinsicContentSize
- (CGSize)intrinsicContentSize {
return _label.intrinsicContentSize;
}
#pragma mark - Apply config
- (void)updateContent {
// Content
_label.attributedText = _config.getRightfulContent.getContentAttributedString;
}
- (void)updateContentStyle {
// Normal background
_label.backgroundColor = _config.getRightfulStyle.backgroundColor;
// Text alignment
_label.textAlignment = _config.getRightfulStyle.textAlignment;
// Gradient background
if (_config.getRightfulStyle.enableGradientBackground) {
_label.backgroundColor = [UIColor clearColor];
((CAGradientLayer *)_label.layer).colors = @[(id)_config.getRightfulStyle.gradientBackgroundStartColor.CGColor,
(id)_config.getRightfulStyle.gradientBackgroundEndColor.CGColor];
((CAGradientLayer *)_label.layer).startPoint = _config.getRightfulStyle.gradientBackgroundStartPoint;
((CAGradientLayer *)_label.layer).endPoint = _config.getRightfulStyle.gradientBackgroundEndPoint;
}
}
- (void)updateFrameWithMaxSize:(CGSize)maxSize {
[_label sizeToFit];
CGSize finalSize = _label.frame.size;
finalSize.width += _config.getRightfulStyle.extraSpace.width;
finalSize.height += _config.getRightfulStyle.extraSpace.height;
if (_config.getRightfulStyle.maxWidth > 0 && finalSize.width > _config.getRightfulStyle.maxWidth) {
finalSize.width = _config.getRightfulStyle.maxWidth;
}
if (_config.getRightfulStyle.minWidth > 0 && finalSize.width < _config.getRightfulStyle.minWidth) {
finalSize.width = _config.getRightfulStyle.minWidth;
}
if (_config.getRightfulStyle.exactWidth > 0) {
finalSize.width = _config.getRightfulStyle.exactWidth;
}
if (_config.getRightfulStyle.exactHeight > 0) {
finalSize.height = _config.getRightfulStyle.exactHeight;
}
if (maxSize.width > 0) {
finalSize.width = MIN(maxSize.width, finalSize.width);
}
if (maxSize.height > 0) {
finalSize.height = MIN(maxSize.height, finalSize.height);
}
CGRect frame = self.frame;
frame.size = finalSize;
self.frame = frame;
_label.frame = self.bounds;
}
- (void)updateShadowWithPath:(UIBezierPath *)path {
self.layer.shadowColor = _config.getRightfulStyle.shadowColor.CGColor;
self.layer.shadowOffset = _config.getRightfulStyle.shadowOffset;
self.layer.shadowRadius = _config.getRightfulStyle.shadowRadius;
self.layer.shadowOpacity = (float)_config.getRightfulStyle.shadowOpacity;
self.layer.shadowPath = path.CGPath;
self.layer.shouldRasterize = YES;
[self.layer setRasterizationScale:[[UIScreen mainScreen] scale]];
}
- (void)updateMaskWithPath:(UIBezierPath *)path {
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bounds;
maskLayer.path = path.CGPath;
_label.layer.mask = maskLayer;
}
- (void)updateBorderWithPath:(UIBezierPath *)path {
if (!_borderLayer) {
_borderLayer = [CAShapeLayer new];
}
[_borderLayer removeFromSuperlayer];
_borderLayer.frame = self.bounds;
_borderLayer.path = path.CGPath;
_borderLayer.fillColor = nil;
_borderLayer.opacity = 1;
_borderLayer.lineWidth = _config.getRightfulStyle.borderWidth;
_borderLayer.strokeColor = _config.getRightfulStyle.borderColor.CGColor;
_borderLayer.lineCap = kCALineCapRound;
_borderLayer.lineJoin = kCALineJoinRound;
[self.layer addSublayer:_borderLayer];
}
- (UIBezierPath *)getNewPath {
// Round corner
UIRectCorner corners = (UIRectCorner)-1;
if (_config.getRightfulStyle.cornerTopLeft) {
corners = UIRectCornerTopLeft;
}
if (_config.getRightfulStyle.cornerTopRight) {
if (corners == -1) {
corners = UIRectCornerTopRight;
} else {
corners = corners | UIRectCornerTopRight;
}
}
if (_config.getRightfulStyle.cornerBottomLeft) {
if (corners == -1) {
corners = UIRectCornerBottomLeft;
} else {
corners = corners | UIRectCornerBottomLeft;
}
}
if (_config.getRightfulStyle.cornerBottomRight) {
if (corners == -1) {
corners = UIRectCornerBottomRight;
} else {
corners = corners | UIRectCornerBottomRight;
}
}
// Corner radius
CGFloat currentCornerRadius = _config.getRightfulStyle.cornerRadius;
// Path
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:corners
cornerRadii:CGSizeMake(currentCornerRadius, currentCornerRadius)];
return path;
}
#pragma mark - Base
- (BOOL)isEqual:(id)other {
if (other == self)
return YES;
if (!other || ![[other class] isEqual:[self class]])
return NO;
return [self isEqualToComponentView:other];
}
- (BOOL)isEqualToComponentView:(TTGTextTagComponentView *)label {
if (self == label)
return YES;
if (label == nil)
return NO;
if (self.config != label.config && ![self.config isEqualToTag:label.config])
return NO;
return YES;
}
- (NSUInteger)hash {
return [self.config hash];
}
@end
#pragma mark - TTGTextTagCollectionView
@interface TTGTextTagCollectionView () <TTGTagCollectionViewDataSource, TTGTagCollectionViewDelegate>
@property (strong, atomic) NSMutableArray <TTGTextTagComponentView *> *tagLabels;
@property (strong, nonatomic) TTGTagCollectionView *tagCollectionView;
@end
@implementation TTGTextTagCollectionView
#pragma mark - Init
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self commonInit];
}
return self;
}
- (void)commonInit {
if (_tagCollectionView) {
return;
}
_enableTagSelection = YES;
_tagLabels = [NSMutableArray new];
_tagCollectionView = [[TTGTagCollectionView alloc] initWithFrame:self.bounds];
_tagCollectionView.delegate = self;
_tagCollectionView.dataSource = self;
_tagCollectionView.horizontalSpacing = 8;
_tagCollectionView.verticalSpacing = 8;
[self addSubview:_tagCollectionView];
}
#pragma mark - Override
- (CGSize)intrinsicContentSize {
return [_tagCollectionView intrinsicContentSize];
}
- (void)layoutSubviews {
[super layoutSubviews];
if (!CGRectEqualToRect(_tagCollectionView.frame, self.bounds)) {
[self updateAllLabelStyleAndFrame];
_tagCollectionView.frame = self.bounds;
[_tagCollectionView setNeedsLayout];
[_tagCollectionView layoutIfNeeded];
[self invalidateIntrinsicContentSize];
}
}
- (CGSize)sizeThatFits:(CGSize)size {
return self.contentSize;
}
#pragma mark - Public methods
- (void)reload {
[self updateAllLabelStyleAndFrame];
[_tagCollectionView reload];
[self invalidateIntrinsicContentSize];
}
- (void)addTag:(TTGTextTag *)tag {
[self insertTag:tag atIndex:_tagLabels.count];
}
- (void)addTags:(NSArray <TTGTextTag *> *)tags {
[self insertTags:tags atIndex:_tagLabels.count];
}
- (void)insertTag:(TTGTextTag *)tag atIndex:(NSUInteger)index {
if ([tag isKindOfClass:[TTGTextTag class]]) {
[self insertTags:@[tag] atIndex:index];
}
}
- (void)insertTags:(NSArray<TTGTextTag *> *)tags atIndex:(NSUInteger)index {
if (![tags isKindOfClass:[NSArray class]] || index > _tagLabels.count || tags.count == 0) {
return;
}
NSMutableArray *newTagLabels = [NSMutableArray new];
for (TTGTextTag *tag in tags) {
if ([tag isKindOfClass:[TTGTextTag class]]) {
TTGTextTagComponentView *label = [self newLabelWithConfig:tag];
[newTagLabels addObject:label];
}
}
[_tagLabels insertObjects:newTagLabels atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index, newTagLabels.count)]];
}
- (void)removeTag:(TTGTextTag *)tag {
if ([tag isKindOfClass:[TTGTextTag class]]) {
[self removeTagById:tag.tagId];
}
}
- (void)removeTagById:(NSUInteger)tagId {
TTGTextTagComponentView *labelToRemove = nil;
for (TTGTextTagComponentView *label in _tagLabels) {
if (label.config.tagId == tagId) {
labelToRemove = label;
}
}
if (labelToRemove) {
[_tagLabels removeObject:labelToRemove];
}
}
- (void)removeTagAtIndex:(NSUInteger)index {
if (index >= _tagLabels.count) {
return;
}
[_tagLabels removeObjectAtIndex:index];
}
- (void)removeAllTags {
[_tagLabels removeAllObjects];
}
- (void)updateTagAtIndex:(NSUInteger)index selected:(BOOL)selected {
TTGTextTag *tag = [self getTagAtIndex:index];
tag.selected = selected;
}
- (void)updateTagAtIndex:(NSUInteger)index withNewTag:(TTGTextTag *)tag {
if (index < _tagLabels.count && [tag isKindOfClass:[TTGTextTag class]]) {
TTGTextTagComponentView *label = _tagLabels[index];
label.config = tag;
[label updateContent];
}
}
- (TTGTextTag *)getTagAtIndex:(NSUInteger)index {
if (index < _tagLabels.count) {
return _tagLabels[index].config;
} else {
return nil;
}
}
- (NSArray<TTGTextTag *> *)getTagsInRange:(NSRange)range {
if (NSMaxRange(range) <= _tagLabels.count) {
NSMutableArray *tags = [NSMutableArray new];
for (TTGTextTagComponentView *label in [_tagLabels subarrayWithRange:range]) {
if (label.config) {
[tags addObject:label.config];
}
}
return [tags copy];
} else {
return nil;
}
}
- (NSArray <TTGTextTag *> *)allTags {
NSMutableArray *allTags = [NSMutableArray new];
for (TTGTextTagComponentView *label in _tagLabels) {
if (label.config) {
[allTags addObject:label.config];
}
}
return [allTags copy];
}
- (NSArray <TTGTextTag *> *)allSelectedTags {
NSMutableArray *allTags = [NSMutableArray new];
for (TTGTextTagComponentView *label in _tagLabels) {
if (label.config.selected) {
[allTags addObject:label.config];
}
}
return [allTags copy];
}
- (NSArray <TTGTextTag *> *)allNotSelectedTags {
NSMutableArray *allTags = [NSMutableArray new];
for (TTGTextTagComponentView *label in _tagLabels) {
if (label.config && !label.config.selected) {
[allTags addObject:label.config];
}
}
return [allTags copy];
}
- (NSInteger)indexOfTagAtPoint:(CGPoint)point {
CGPoint convertedPoint = [self convertPoint:point toView:_tagCollectionView];
return [_tagCollectionView indexOfTagAt:convertedPoint];
}
#pragma mark - TTGTagCollectionViewDataSource
- (NSUInteger)numberOfTagsInTagCollectionView:(TTGTagCollectionView *)tagCollectionView {
return _tagLabels.count;
}
- (UIView *)tagCollectionView:(TTGTagCollectionView *)tagCollectionView tagViewForIndex:(NSUInteger)index {
return _tagLabels[index];
}
#pragma mark - TTGTagCollectionViewDelegate
- (BOOL)tagCollectionView:(TTGTagCollectionView *)tagCollectionView shouldSelectTag:(UIView *)tagView atIndex:(NSUInteger)index {
if (_enableTagSelection) {
TTGTextTagComponentView *label = _tagLabels[index];
if ([self.delegate respondsToSelector:@selector(textTagCollectionView:canTapTag:atIndex:)]) {
return [self.delegate textTagCollectionView:self canTapTag:label.config atIndex:index];
} else {
return YES;
}
} else {
return NO;
}
}
- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView didSelectTag:(UIView *)tagView atIndex:(NSUInteger)index {
if (_enableTagSelection) {
TTGTextTagComponentView *label = _tagLabels[index];
if (_selectionLimit == 1) {
for (TTGTextTagComponentView *tag in _tagLabels) {
tag.config.selected = false;
}
}
label.config.selected = !label.config.selected;
if (self.alignment == TTGTagCollectionAlignmentFillByExpandingWidth ||
self.alignment == TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine) {
[self reload];
} else {
[self updateStyleAndFrameForLabel:label];
}
if ([_delegate respondsToSelector:@selector(textTagCollectionView:didTapTag:atIndex:)]) {
[_delegate textTagCollectionView:self didTapTag:label.config atIndex:index];
}
}
}
- (CGSize)tagCollectionView:(TTGTagCollectionView *)tagCollectionView sizeForTagAtIndex:(NSUInteger)index {
return _tagLabels[index].frame.size;
}
- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView updateContentSize:(CGSize)contentSize {
if ([_delegate respondsToSelector:@selector(textTagCollectionView:updateContentSize:)]) {
[_delegate textTagCollectionView:self updateContentSize:contentSize];
}
}
#pragma mark - Setter and Getter
- (UIScrollView *)scrollView {
return _tagCollectionView.scrollView;
}
- (CGFloat)horizontalSpacing {
return _tagCollectionView.horizontalSpacing;
}
- (void)setHorizontalSpacing:(CGFloat)horizontalSpacing {
_tagCollectionView.horizontalSpacing = horizontalSpacing;
}
- (CGFloat)verticalSpacing {
return _tagCollectionView.verticalSpacing;
}
- (void)setVerticalSpacing:(CGFloat)verticalSpacing {
_tagCollectionView.verticalSpacing = verticalSpacing;
}
- (CGSize)contentSize {
return _tagCollectionView.contentSize;
}
- (TTGTagCollectionScrollDirection)scrollDirection {
return _tagCollectionView.scrollDirection;
}
- (void)setScrollDirection:(TTGTagCollectionScrollDirection)scrollDirection {
_tagCollectionView.scrollDirection = scrollDirection;
}
- (TTGTagCollectionAlignment)alignment {
return _tagCollectionView.alignment;
}
- (void)setAlignment:(TTGTagCollectionAlignment)alignment {
_tagCollectionView.alignment = alignment;
}
- (NSUInteger)numberOfLines {
return _tagCollectionView.numberOfLines;
}
- (void)setNumberOfLines:(NSUInteger)numberOfLines {
_tagCollectionView.numberOfLines = numberOfLines;
}
- (NSUInteger)actualNumberOfLines {
return _tagCollectionView.actualNumberOfLines;
}
- (UIEdgeInsets)contentInset {
return _tagCollectionView.contentInset;
}
- (void)setContentInset:(UIEdgeInsets)contentInset {
_tagCollectionView.contentInset = contentInset;
}
- (BOOL)manualCalculateHeight {
return _tagCollectionView.manualCalculateHeight;
}
- (void)setManualCalculateHeight:(BOOL)manualCalculateHeight {
_tagCollectionView.manualCalculateHeight = manualCalculateHeight;
}
- (CGFloat)preferredMaxLayoutWidth {
return _tagCollectionView.preferredMaxLayoutWidth;
}
- (void)setPreferredMaxLayoutWidth:(CGFloat)preferredMaxLayoutWidth {
_tagCollectionView.preferredMaxLayoutWidth = preferredMaxLayoutWidth;
}
- (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator {
_tagCollectionView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
}
- (BOOL)showsHorizontalScrollIndicator {
return _tagCollectionView.showsHorizontalScrollIndicator;
}
- (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator {
_tagCollectionView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
}
- (BOOL)showsVerticalScrollIndicator {
return _tagCollectionView.showsVerticalScrollIndicator;
}
- (void)setOnTapBlankArea:(void (^)(CGPoint location))onTapBlankArea {
_tagCollectionView.onTapBlankArea = onTapBlankArea;
}
- (void (^)(CGPoint location))onTapBlankArea {
return _tagCollectionView.onTapBlankArea;
}
- (void)setOnTapAllArea:(void (^)(CGPoint location))onTapAllArea {
_tagCollectionView.onTapAllArea = onTapAllArea;
}
- (void (^)(CGPoint location))onTapAllArea {
return _tagCollectionView.onTapAllArea;
}
#pragma mark - Private methods
- (void)updateAllLabelStyleAndFrame {
for (TTGTextTagComponentView *label in _tagLabels) {
[self updateStyleAndFrameForLabel:label];
}
}
- (void)updateStyleAndFrameForLabel:(TTGTextTagComponentView *)label {
// Update content
[label updateContent];
// Update content style
[label updateContentStyle];
// Width limit for vertical scroll direction
CGSize maxSize = CGSizeZero;
if (self.scrollDirection == TTGTagCollectionScrollDirectionVertical &&
CGRectGetWidth(self.bounds) > 0) {
maxSize.width = (CGRectGetWidth(self.bounds) - self.contentInset.left - self.contentInset.right);
}
// Update frame
[label updateFrameWithMaxSize:maxSize];
}
- (TTGTextTagComponentView *)newLabelWithConfig:(TTGTextTag *)config {
TTGTextTagComponentView *label = [TTGTextTagComponentView new];
label.config = config;
return label;
}
@end

View File

@ -0,0 +1,23 @@
//
// TTGTextTagContent.h
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
Base content class.
Do not use this class directly!
*/
@interface TTGTextTagContent : NSObject <NSCopying>
/// Must be override by subClass
- (NSAttributedString *_Nonnull)getContentAttributedString;
/// Must be override by subClass
- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone;
@end

View File

@ -0,0 +1,22 @@
//
// TTGTextTagContent.m
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTagContent.h"
@implementation TTGTextTagContent
- (NSAttributedString *)getContentAttributedString {
NSAssert(NO, @"Do not use TTGTextTagContent directly.");
return [NSAttributedString new];
}
- (id)copyWithZone:(NSZone *)zone {
return [[[self class] allocWithZone:zone] init];
}
@end

View File

@ -0,0 +1,39 @@
//
// TTGTextTagStringContent.h
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTagContent.h"
/**
Normal text content with custom font and color.
*/
@interface TTGTextTagStringContent : TTGTextTagContent
/// Text
@property (nonatomic, copy) NSString * _Nonnull text;
/// Text font
@property (nonatomic, copy) UIFont * _Nonnull textFont;
/// Text color
@property (nonatomic, copy) UIColor * _Nonnull textColor;
/// Init
- (instancetype _Nonnull)initWithText:(NSString *_Nonnull)text;
- (instancetype _Nonnull)initWithText:(NSString *_Nonnull)text
textFont:(UIFont *_Nullable)textFont
textColor:(UIColor *_Nullable)textColor;
/// Content
+ (instancetype _Nonnull)contentWithText:(NSString *_Nonnull)text;
+ (instancetype _Nonnull)contentWithText:(NSString *_Nonnull)text
textFont:(UIFont *_Nullable)textFont
textColor:(UIColor *_Nullable)textColor;
/// Base system methods
- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone;
- (NSString *_Nonnull)description;
@end

View File

@ -0,0 +1,80 @@
//
// TTGTextTagStringContent.m
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTagStringContent.h"
@implementation TTGTextTagStringContent
- (instancetype)initWithText:(NSString *)text {
self = [super init];
if (self) {
self.text = text;
}
return self;
}
+ (instancetype)contentWithText:(NSString *)text {
return [[self alloc] initWithText:text];
}
- (instancetype)initWithText:(NSString *)text
textFont:(UIFont *)textFont
textColor:(UIColor *)textColor {
self = [super init];
if (self) {
self.text = text;
self.textFont = textFont;
self.textColor = textColor;
}
return self;
}
+ (instancetype)contentWithText:(NSString *)text
textFont:(UIFont *)textFont
textColor:(UIColor *)textColor {
return [[self alloc] initWithText:text
textFont:textFont
textColor:textColor];
}
- (NSAttributedString *)getContentAttributedString {
return [[NSAttributedString alloc] initWithString:self.text
attributes:@{NSForegroundColorAttributeName: self.textColor,
NSFontAttributeName: self.textFont}];
}
- (NSString *)text {
return _text ?: @"";
}
- (UIFont *)textFont {
return _textFont ?: [UIFont systemFontOfSize:14];
}
- (UIColor *)textColor {
return _textColor ?: [UIColor blackColor];
}
- (id)copyWithZone:(NSZone *)zone {
TTGTextTagStringContent *copy = (TTGTextTagStringContent *)[super copyWithZone:zone];
if (copy != nil) {
copy.text = self.text;
copy.textFont = self.textFont;
copy.textColor = self.textColor;
}
return copy;
}
- (NSString *)description {
NSMutableString *description = [NSMutableString stringWithFormat:@"<%@: ", NSStringFromClass([self class])];
[description appendFormat:@"self.text=%@", self.text];
[description appendString:@">"];
return description;
}
@end

View File

@ -0,0 +1,65 @@
//
// TTGTextTagStyle.h
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface TTGTextTagStyle : NSObject <NSCopying>
/// Background color
@property (nonatomic, copy) UIColor * _Nonnull backgroundColor; // Default is [UIColor lightGrayColor]
/// Text alignment
@property (nonatomic, assign) NSTextAlignment textAlignment; // Default is NSTextAlignmentCenter
/// Gradient background color
@property (nonatomic, assign) BOOL enableGradientBackground; // Default is NO
@property (nonatomic, copy) UIColor * _Nonnull gradientBackgroundStartColor;
@property (nonatomic, copy) UIColor * _Nonnull gradientBackgroundEndColor;
@property (nonatomic, assign) CGPoint gradientBackgroundStartPoint;
@property (nonatomic, assign) CGPoint gradientBackgroundEndPoint;
/// Corner radius
@property (nonatomic, assign) CGFloat cornerRadius; // Default is 4
@property (nonatomic, assign) Boolean cornerTopRight;
@property (nonatomic, assign) Boolean cornerTopLeft;
@property (nonatomic, assign) Boolean cornerBottomRight;
@property (nonatomic, assign) Boolean cornerBottomLeft;
/// Border
@property (nonatomic, assign) CGFloat borderWidth; // Default is [UIColor whiteColor]
@property (nonatomic, copy) UIColor * _Nonnull borderColor; // Default is 1
/// Shadow.
@property (nonatomic, copy) UIColor * _Nonnull shadowColor; // Default is [UIColor blackColor]
@property (nonatomic, assign) CGSize shadowOffset; // Default is (2, 2)
@property (nonatomic, assign) CGFloat shadowRadius; // Default is 2f
@property (nonatomic, assign) CGFloat shadowOpacity; // Default is 0.3f
/// Extra space in width and height, will expand each tag's size
@property (nonatomic, assign) CGSize extraSpace;
/// Max width for a text tag. 0 and below means no max width.
@property (nonatomic, assign) CGFloat maxWidth;
/// Min width for a text tag. 0 and below means no min width.
@property (nonatomic, assign) CGFloat minWidth;
/// Max height for a text tag. 0 and below means no max height.
@property (nonatomic, assign) CGFloat maxHeight;
/// Min height for a text tag. 0 and below means no min height.
@property (nonatomic, assign) CGFloat minHeight;
/// Exact width. 0 and below means no work
@property (nonatomic, assign) CGFloat exactWidth;
/// Exact height. 0 and below means no work
@property (nonatomic, assign) CGFloat exactHeight;
/// Copy
- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone;
@end

View File

@ -0,0 +1,84 @@
//
// TTGTextTagStyle.m
// TTGTagCollectionView
//
// Created by zekunyan on 2019/5/24.
// Copyright (c) 2021 zekunyan. All rights reserved.
//
#import "TTGTextTagStyle.h"
@implementation TTGTextTagStyle
- (instancetype)init {
self = [super init];
if (self) {
_backgroundColor = [UIColor lightGrayColor];
_textAlignment = NSTextAlignmentCenter;
_enableGradientBackground = NO;
_cornerRadius = 4;
_borderColor = [UIColor whiteColor];
_borderWidth = 1;
_shadowColor = [UIColor blackColor];
_shadowOffset = CGSizeMake(2, 2);
_shadowRadius = 2;
_shadowOpacity = 0.3;
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
TTGTextTagStyle *copy = (TTGTextTagStyle *)[[[self class] allocWithZone:zone] init];
if (copy != nil) {
copy.backgroundColor = self.backgroundColor;
copy.textAlignment = self.textAlignment;
copy.enableGradientBackground = self.enableGradientBackground;
copy.gradientBackgroundStartColor = self.gradientBackgroundStartColor;
copy.gradientBackgroundEndColor = self.gradientBackgroundEndColor;
copy.gradientBackgroundStartPoint = self.gradientBackgroundStartPoint;
copy.gradientBackgroundEndPoint = self.gradientBackgroundEndPoint;
copy.cornerRadius = self.cornerRadius;
copy.cornerTopRight = self.cornerTopRight;
copy.cornerTopLeft = self.cornerTopLeft;
copy.cornerBottomRight = self.cornerBottomRight;
copy.cornerBottomLeft = self.cornerBottomLeft;
copy.borderWidth = self.borderWidth;
copy.borderColor = self.borderColor;
copy.shadowColor = self.shadowColor;
copy.shadowOffset = self.shadowOffset;
copy.shadowRadius = self.shadowRadius;
copy.shadowOpacity = self.shadowOpacity;
copy.extraSpace = self.extraSpace;
copy.maxWidth = self.maxWidth;
copy.minWidth = self.minWidth;
copy.maxHeight = self.maxHeight;
copy.minHeight = self.minHeight;
copy.exactWidth = self.exactWidth;
copy.exactHeight = self.exactHeight;
}
return copy;
}
- (UIColor *)backgroundColor {
return _backgroundColor ?: [UIColor clearColor];
}
- (UIColor *)gradientBackgroundStartColor {
return _gradientBackgroundStartColor ?: [UIColor clearColor];
}
- (UIColor *)gradientBackgroundEndColor {
return _gradientBackgroundEndColor ?: [UIColor clearColor];
}
- (UIColor *)borderColor {
return _borderColor ?: [UIColor clearColor];
}
- (UIColor *)shadowColor {
return _shadowColor ?: [UIColor clearColor];
}
@end