From 0cf49071e27d6c99fa5298e74e9fb33e19bcd8b1 Mon Sep 17 00:00:00 2001 From: Ekko Date: Thu, 26 May 2022 15:35:22 +0800 Subject: [PATCH] make setTitleColor work with title set of UButton, try to fix #38 --- Classes/Views/Not-MacOS/Button.swift | 33 +++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/Classes/Views/Not-MacOS/Button.swift b/Classes/Views/Not-MacOS/Button.swift index e34b8818..56703b1d 100644 --- a/Classes/Views/Not-MacOS/Button.swift +++ b/Classes/Views/Not-MacOS/Button.swift @@ -52,11 +52,25 @@ open class UButton: UIButton, AnyDeclarativeProtocol, DeclarativeProtocolInterna open override func setAttributedTitle(_ title: NSAttributedString?, for state: UIControl.State) { guard let transition = titleChangeTransition else { - super.setAttributedTitle(title, for: state) + if let title = title { + let color = self.titleColor(for: state) + let mutable = NSMutableAttributedString(attributedString: title) + mutable.addAttribute(.foregroundColor, value: color, range: NSRange(location: 0, length: mutable.length)) + super.setAttributedTitle(mutable, for: state) + } else { + super.setAttributedTitle(title, for: state) + } return } UIView.transition(with: self, duration: 0.25, options: transition, animations: { - super.setAttributedTitle(title, for: state) + if let title = title { + let color = self.titleColor(for: state) + let mutable = NSMutableAttributedString(attributedString: title) + mutable.addAttribute(.foregroundColor, value: color, range: NSRange(location: 0, length: mutable.length)) + super.setAttributedTitle(mutable, for: state) + } else { + super.setAttributedTitle(title, for: state) + } }, completion: nil) } @@ -215,7 +229,20 @@ open class UButton: UIButton, AnyDeclarativeProtocol, DeclarativeProtocolInterna } // MARK: Title Color - + open override func setTitleColor(_ color: UIColor?, for state: State) { + if #available(iOS 14.0, *) { + super.setTitleColor(color, for: state) + } + else { + let attibutedString = attributedTitle(for: state) + if let color = color, let attibutedString = attributedTitle(for: state) { + let mutable = NSMutableAttributedString(attributedString: attibutedString) + mutable.addAttribute(.foregroundColor, value: color, range: NSRange(location: 0, length: mutable.length)) + super.setAttributedTitle(mutable, for: state) + } + } + } + @discardableResult public func color(_ color: UIColor, _ state: UIControl.State = .normal) -> Self { setTitleColor(color, for: state)