-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSTBtn.swift
More file actions
589 lines (532 loc) · 22.7 KB
/
Copy pathSTBtn.swift
File metadata and controls
589 lines (532 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//
// STBtn.swift
// STBaseProject
//
// Created by 寒江孤影 on 2019/10/14.
//
import UIKit
private enum STBtnLocalizationKey {
static var localizedTitleKey: UInt8 = 0
static var localizedSelectedTitleKey: UInt8 = 1
}
public enum STBtnBackgroundStyle: Int {
case normal = 0
case gradient = 1
case liquidGlass = 2
}
@IBDesignable
open class STBtn: UIButton {
/// 通用标识符,已废弃。
/// `Any?` 无法提供类型安全、也无法稳定契约化。请改用:
/// - 字符串标识:`stringIdentifier`
/// - 整数标识:`tag`(UIKit 原生)
/// - 无障碍/UI 测试标识:`accessibilityIdentifier`
@available(*, deprecated, message: "Use stringIdentifier, tag, or accessibilityIdentifier instead.")
open var identifier: Any?
private var gradientLayer: CAGradientLayer?
private var gradientColors: [UIColor]?
private var gradientStartPoint = CGPoint(x: 0, y: 0)
private var gradientEndPoint = CGPoint(x: 1, y: 1)
private var liquidGlassView: STLiquidGlassView?
/// 按 `UIControl.State.rawValue` 存储的 Configuration 背景色,由 `st_setBackgroundColor(_:for:)` 维护。
private var stateBackgroundColors: [UInt: UIColor] = [:]
public var backgroundStyle: STBtnBackgroundStyle = .normal {
didSet {
guard oldValue != self.backgroundStyle else { return }
self.updateBackgroundStyle()
}
}
@IBInspectable open var backgroundStyleRaw: Int {
get {
return self.backgroundStyle.rawValue
}
set {
guard let style = STBtnBackgroundStyle(rawValue: newValue) else { return }
self.backgroundStyle = style
}
}
@IBInspectable open var isLiquidGlassEnabled: Bool {
get {
return self.backgroundStyle == .liquidGlass
}
set {
self.backgroundStyle = newValue ? .liquidGlass : .normal
}
}
@IBInspectable open var liquidGlassTintColor: UIColor = UIColor.white.withAlphaComponent(0.18) {
didSet {
self.updateLiquidGlassAppearance()
}
}
@IBInspectable open var liquidGlassHighlightOpacity: Float = 0.45 {
didSet {
self.updateLiquidGlassAppearance()
}
}
@IBInspectable open var liquidGlassBorderColor: UIColor = UIColor.white.withAlphaComponent(0.45) {
didSet {
self.updateLiquidGlassAppearance()
}
}
/// 字符串标识符(类型安全,推荐使用)
/// 使用示例:
/// ```
/// button.stringIdentifier = "home_button"
/// if button.stringIdentifier == "home_button" { ... }
/// ```
/// 注意:对于整数标识符,请使用 `tag` 属性:
/// ```
/// button.tag = 100
/// if button.tag == 100 { ... }
/// ```
@IBInspectable open var stringIdentifier: String?
/// 传入 Localization **key**,setter 通过 `String.localized` 扩展立即解析为当前语言文案并写入 `.normal` title。
///
/// 行为说明:
/// - 传入值是 key(会查 `Localizable.strings`),不是最终文案;
/// - 原始 key 通过关联对象保存,可通过 getter 回读;
/// - 解析发生在赋值时刻,**不会自动响应运行时语言切换**;如需切换语言后刷新,请重新赋值或在语言切换通知中再次调用。
@IBInspectable open var localizedTitle: String {
get {
return objc_getAssociatedObject(self, &STBtnLocalizationKey.localizedTitleKey) as? String ?? ""
}
set {
objc_setAssociatedObject(self, &STBtnLocalizationKey.localizedTitleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.setTitle(newValue.localized, for: .normal)
}
}
/// 传入 Localization **key**,setter 通过 `String.localized` 扩展立即解析为当前语言文案并写入 `.selected` title。
/// 行为与 `localizedTitle` 一致,**不会自动响应运行时语言切换**。
@IBInspectable open var localizedSelectedTitle: String {
get {
return objc_getAssociatedObject(self, &STBtnLocalizationKey.localizedSelectedTitleKey) as? String ?? ""
}
set {
objc_setAssociatedObject(self, &STBtnLocalizationKey.localizedSelectedTitleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.setTitle(newValue.localized, for: .selected)
}
}
@IBInspectable open var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
@IBInspectable open var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
self.updateGradientLayerCornerRadius()
self.updateLiquidGlassCornerRadius()
self.setNeedsUpdateConfiguration()
}
}
@IBInspectable open var clipsContentToBounds: Bool {
get {
return self.layer.masksToBounds
}
set {
self.layer.masksToBounds = newValue
}
}
@IBInspectable open var borderColor: UIColor? {
get {
guard let color = self.layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
set {
self.layer.borderColor = newValue?.cgColor
}
}
/// 它只在开启时读取当前字号、用项目字体重建一个同字号的 `UIFont`,用于统一品牌字体。
/// 如需"文本自动缩放以适配宽度",请另设 `titleLabel?.adjustsFontSizeToFitWidth` 与 `minimumScaleFactor`。
@IBInspectable open var autoAdaptFontSize: Bool = true {
didSet {
if self.autoAdaptFontSize {
self.updateFontSize()
}
}
}
/// 阴影偏移宽度(IBInspectable)
@IBInspectable open var shadowOffsetWidth: CGFloat {
get {
return self.layer.shadowOffset.width
}
set {
self.layer.shadowOffset = CGSize(width: newValue, height: self.layer.shadowOffset.height)
}
}
/// 阴影偏移高度(IBInspectable)
@IBInspectable open var shadowOffsetHeight: CGFloat {
get {
return self.layer.shadowOffset.height
}
set {
self.layer.shadowOffset = CGSize(width: self.layer.shadowOffset.width, height: newValue)
}
}
/// 阴影半径(IBInspectable)
@IBInspectable open var shadowRadius: CGFloat {
get {
return self.layer.shadowRadius
}
set {
self.layer.shadowRadius = newValue
}
}
/// 阴影透明度(IBInspectable,范围 0.0-1.0)
@IBInspectable open var shadowOpacity: Float {
get {
return self.layer.shadowOpacity
}
set {
self.layer.shadowOpacity = newValue
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.setupButton()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupButton()
}
override open var isHighlighted: Bool {
didSet {
self.updateLiquidGlassState(animated: true)
}
}
override open var isEnabled: Bool {
didSet {
self.updateLiquidGlassState(animated: false)
}
}
/// STBtn 上次写入 `config.background.backgroundColor` 的值。
/// `stateBackgroundColors` 被清空后,仅在"当前背景色仍等于我们上次写入的值"时才清掉 `backgroundColor`,
/// 避免误伤调用方通过 `onConfigurationUpdate` 另行设置的背景色。
private var lastManagedBackgroundColor: UIColor?
private var hasPreservedSystemStateTransformers = false
private var preservedImageColorTransformer: UIConfigurationColorTransformer?
private var preservedBackgroundColorTransformer: UIConfigurationColorTransformer?
/// 是否屏蔽 `UIButton.Configuration` 的系统默认状态效果
/// (`highlighted` 下标题/图标 alpha 衰减、`disabled` 灰化、background 自动 tint)。
///
/// - `false`(**默认**):保留 UIKit 原生状态反馈,STBtn 行为等同 UIButton,
/// 开发者使用 `UIButton.Configuration.filled/tinted/gray()`、设置 `baseBackgroundColor`、
/// 读取系统 `highlighted` tint 等标准 API 都符合 Apple 文档预期。
/// - `true`:屏蔽系统状态效果,标题色 / 图标色 / 背景色完全由调用方通过
/// `setTitleColor(_:for:)` / `setImage(_:for:)` / `st_setBackgroundColor(_:for:)` /
/// `onConfigurationUpdate` 接口显式接管。适合强品牌规范、不允许系统 tint 干扰的场景。
///
/// ⚠️ 从 2.x 起默认值从 `true` 翻转为 `false`;若升级后视觉变化明显,
/// 在按钮创建后显式设置 `btn.suppressesSystemStateEffects = true` 即可恢复旧行为。
public var suppressesSystemStateEffects: Bool = false {
didSet {
guard oldValue != self.suppressesSystemStateEffects else { return }
if self.suppressesSystemStateEffects {
self.preserveSystemStateTransformersIfNeeded()
} else {
self.restorePreservedSystemStateTransformers()
}
self.setNeedsUpdateConfiguration()
}
}
/// 外部扩展点:每次 Configuration 更新时在 STBtn 内部逻辑 **之后** 调用,
/// 允许调用方追加字段调整而不必直接接管 `configurationUpdateHandler`。
/// ⚠️ 请勿直接给 `self.configurationUpdateHandler` 赋值 —— 那会把 STBtn 的 `contentInsets`、
/// state 背景、字体注入等逻辑全部覆盖。所有"每次 update 要做的事"都应写在这里。
///
/// 赋值后会自动触发一次 `setNeedsUpdateConfiguration()`,使闭包"设置即生效"。
///
/// 使用示例:
/// ```
/// button.onConfigurationUpdate = { btn, config in
/// config.background.strokeColor = btn.isSelected ? .systemBlue : .clear
/// config.background.strokeWidth = 1
/// }
/// ```
public var onConfigurationUpdate: ((UIButton, inout UIButton.Configuration) -> Void)? {
didSet {
self.setNeedsUpdateConfiguration()
}
}
private func setupButton() {
self.titleLabel?.adjustsFontForContentSizeCategory = true
self.titleLabel?.textAlignment = .natural
self.titleLabel?.numberOfLines = 1
self.titleLabel?.lineBreakMode = .byTruncatingTail
self.imageView?.contentMode = .scaleAspectFit
self.installModernButtonConfiguration()
}
/// `UIButton.Configuration`,以及 update handler 用于:
/// - 注入 `titleLabel.font` 到 `attributedTitle`
/// - 根据 `suppressesSystemStateEffects` 选择性屏蔽系统状态效果
/// - 同步 corner radius 与 state 背景色
/// - 回调 `onConfigurationUpdate` 扩展点
///
private func installModernButtonConfiguration() {
if self.configuration == nil {
let xibFont = self.titleLabel?.font
self.configuration = UIButton.Configuration.plain()
if let font = xibFont {
self.titleLabel?.font = font
}
}
self.configurationUpdateHandler = { [weak self] button in
guard let self, var config = button.configuration else { return }
config.titleLineBreakMode = .byTruncatingTail
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { [weak self] attrs in
var updated = attrs
guard let self else { return updated }
if let font = self.titleLabel?.font {
updated.font = font
}
if self.suppressesSystemStateEffects,
let color = self.titleColor(for: self.state) {
updated.foregroundColor = color
}
return updated
}
if self.suppressesSystemStateEffects {
config.imageColorTransformer = UIConfigurationColorTransformer { $0 }
}
self.refineButtonConfiguration(button, configuration: &config)
self.onConfigurationUpdate?(button, &config)
button.configuration = config
self.titleLabel?.numberOfLines = 1
self.titleLabel?.lineBreakMode = .byTruncatingTail
}
self.setNeedsUpdateConfiguration()
}
private func preserveSystemStateTransformersIfNeeded() {
guard !self.hasPreservedSystemStateTransformers else { return }
self.preservedImageColorTransformer = self.configuration?.imageColorTransformer
self.preservedBackgroundColorTransformer = self.configuration?.background.backgroundColorTransformer
self.hasPreservedSystemStateTransformers = true
}
private func restorePreservedSystemStateTransformers() {
guard self.hasPreservedSystemStateTransformers else { return }
if var config = self.configuration {
config.imageColorTransformer = self.preservedImageColorTransformer
config.background.backgroundColorTransformer = self.preservedBackgroundColorTransformer
self.configuration = config
}
self.preservedImageColorTransformer = nil
self.preservedBackgroundColorTransformer = nil
self.hasPreservedSystemStateTransformers = false
}
/// 子类(如 `STIconBtn`)覆写此方法以写入图文布局 / `contentInsets` 等 Configuration 字段。
/// 调用时机:每次 `configurationUpdateHandler` 触发,在字体/状态 transformer 之后、`onConfigurationUpdate` 之前。
open func refineButtonConfiguration(_ button: UIButton, configuration config: inout UIButton.Configuration) {
// iOS 26 changed UIButton.Configuration.plain() defaults: non-nil symbol config
// and non-zero content insets. Both are cleared here so custom PNG images render
// at their natural size. Callers can restore via onConfigurationUpdate.
config.preferredSymbolConfigurationForImage = nil
config.contentInsets = .zero
config.imagePadding = 0
config.background.cornerRadius = self.layer.cornerRadius
let resolvedBackgroundColor = self.resolvedStateBackgroundColor(for: button.state)
if self.suppressesSystemStateEffects {
config.background.backgroundColorTransformer = UIConfigurationColorTransformer { $0 }
if resolvedBackgroundColor == nil {
config.baseBackgroundColor = .clear
config.background.backgroundColor = .clear
}
}
if let color = resolvedBackgroundColor {
config.background.backgroundColor = color
self.lastManagedBackgroundColor = color
} else if let managed = self.lastManagedBackgroundColor, config.background.backgroundColor == managed {
config.background.backgroundColor = nil
self.lastManagedBackgroundColor = nil
}
}
override open func layoutSubviews() {
super.layoutSubviews()
self.updateGradientLayerFrame()
self.updateLiquidGlassFrame()
}
/// 设置圆角按钮
/// - Parameter cornerRadius: 圆角半径
public func st_roundedButton(cornerRadius: CGFloat) {
self.st_roundedButton(cornerRadius: cornerRadius, borderWidth: 0, borderColor: UIColor.clear)
}
/// 设置圆角按钮
/// - Parameters:
/// - cornerRadius: 圆角半径
/// - borderWidth: 边框宽度
/// - borderColor: 边框颜色
public func st_roundedButton(cornerRadius: CGFloat, borderWidth: CGFloat, borderColor: UIColor) {
self.cornerRadius = cornerRadius
self.clipsContentToBounds = true
self.borderWidth = borderWidth
self.borderColor = borderColor
}
/// 设置渐变背景
/// - Parameters:
/// - colors: 渐变色数组
/// - startPoint: 起始点
/// - endPoint: 结束点
public func st_setGradientBackground(colors: [UIColor], startPoint: CGPoint = CGPoint(x: 0, y: 0), endPoint: CGPoint = CGPoint(x: 1, y: 1)) {
self.gradientColors = colors
self.gradientStartPoint = startPoint
self.gradientEndPoint = endPoint
self.backgroundStyle = .gradient
self.updateBackgroundStyle()
}
public func st_setLiquidGlassBackground(
tintColor: UIColor = UIColor.white.withAlphaComponent(0.18),
highlightOpacity: Float = 0.45,
borderColor: UIColor = UIColor.white.withAlphaComponent(0.45)
) {
self.liquidGlassTintColor = tintColor
self.liquidGlassHighlightOpacity = highlightOpacity
self.liquidGlassBorderColor = borderColor
self.backgroundStyle = .liquidGlass
self.updateBackgroundStyle()
}
/// 设置阴影
/// - Parameters:
/// - color: 阴影颜色
/// - offset: 阴影偏移
/// - radius: 阴影半径
/// - opacity: 阴影透明度
override public func st_setShadow(color: UIColor = .black, offset: CGSize = CGSize(width: 0, height: 2), radius: CGFloat = 4, opacity: Float = 0.3) {
self.layer.shadowColor = color.cgColor
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.masksToBounds = false
}
/// 按状态设置按钮背景色(写入 `UIButton.Configuration.background.backgroundColor`)。
///
/// 命中优先级:`disabled` > `highlighted` > `selected` > `normal`;未设置的状态回退到 `.normal`。
/// 传入 `nil` 清除该状态的设置。
///
/// 使用示例:
/// ```
/// button.st_setBackgroundColor(.systemBlue, for: .normal)
/// button.st_setBackgroundColor(.systemIndigo, for: .highlighted)
/// button.st_setBackgroundColor(.systemGray3, for: .disabled)
/// ```
public func st_setBackgroundColor(_ color: UIColor?, for state: UIControl.State) {
let key = state.rawValue
if let color {
self.stateBackgroundColors[key] = color
} else {
self.stateBackgroundColors.removeValue(forKey: key)
}
self.setNeedsUpdateConfiguration()
}
/// 读取指定状态下已设置的背景色(不含回退推导)。
public func st_backgroundColor(for state: UIControl.State) -> UIColor? {
return self.stateBackgroundColors[state.rawValue]
}
/// 按当前 `button.state` 解析实际命中的背景色,内部使用。
private func resolvedStateBackgroundColor(for state: UIControl.State) -> UIColor? {
guard !self.stateBackgroundColors.isEmpty else { return nil }
if let color = self.stateBackgroundColors[state.rawValue] {
return color
}
if state.contains(.disabled), let color = self.stateBackgroundColors[UIControl.State.disabled.rawValue] {
return color
}
if state.contains(.highlighted), let color = self.stateBackgroundColors[UIControl.State.highlighted.rawValue] {
return color
}
if state.contains(.selected), let color = self.stateBackgroundColors[UIControl.State.selected.rawValue] {
return color
}
return self.stateBackgroundColors[UIControl.State.normal.rawValue]
}
private func updateFontSize() {
guard let fontSize = self.titleLabel?.font.pointSize else { return }
self.titleLabel?.font = UIFont.st_systemFont(ofSize: fontSize)
}
private func updateBackgroundStyle() {
switch self.backgroundStyle {
case .normal:
self.removeGradientLayer()
self.removeLiquidGlassView()
case .gradient:
self.removeLiquidGlassView()
self.updateGradientLayer()
case .liquidGlass:
self.removeGradientLayer()
self.updateLiquidGlassView()
}
}
private func updateGradientLayer() {
guard let colors = self.gradientColors else { return }
let gradientLayer = self.gradientLayer ?? CAGradientLayer()
gradientLayer.colors = colors.map { $0.cgColor }
gradientLayer.startPoint = self.gradientStartPoint
gradientLayer.endPoint = self.gradientEndPoint
gradientLayer.frame = self.bounds
gradientLayer.cornerRadius = self.layer.cornerRadius
if gradientLayer.superlayer == nil {
self.layer.insertSublayer(gradientLayer, at: 0)
}
self.gradientLayer = gradientLayer
}
private func removeGradientLayer() {
self.gradientLayer?.removeFromSuperlayer()
self.gradientLayer = nil
}
private func updateGradientLayerFrame() {
guard let gradientLayer = self.gradientLayer else { return }
gradientLayer.frame = self.bounds
gradientLayer.cornerRadius = self.layer.cornerRadius
}
private func updateGradientLayerCornerRadius() {
self.gradientLayer?.cornerRadius = self.layer.cornerRadius
}
private func updateLiquidGlassView() {
let glassView = self.liquidGlassView ?? STLiquidGlassView()
if glassView.superview == nil {
self.insertSubview(glassView, at: 0)
}
self.liquidGlassView = glassView
self.updateLiquidGlassFrame()
self.updateLiquidGlassAppearance()
}
private func updateLiquidGlassFrame() {
guard let glassView = self.liquidGlassView else { return }
glassView.frame = self.bounds
glassView.glassCornerRadius = self.layer.cornerRadius
self.sendSubviewToBack(glassView)
}
private func updateLiquidGlassAppearance() {
guard let glassView = self.liquidGlassView else { return }
glassView.configure(
tintColor: self.liquidGlassTintColor,
highlightOpacity: self.liquidGlassHighlightOpacity,
borderColor: self.liquidGlassBorderColor,
cornerRadius: self.layer.cornerRadius
)
self.updateLiquidGlassState(animated: false)
}
private func updateLiquidGlassCornerRadius() {
self.liquidGlassView?.glassCornerRadius = self.layer.cornerRadius
}
private func updateLiquidGlassState(animated: Bool) {
guard let glassView = self.liquidGlassView else { return }
let alpha: CGFloat
if !self.isEnabled {
alpha = 0.45
} else if self.isHighlighted {
alpha = 0.82
} else {
alpha = 1
}
glassView.setStateAlpha(alpha, animated: animated)
}
private func removeLiquidGlassView() {
self.liquidGlassView?.removeFromSuperview()
self.liquidGlassView = nil
}
}