您可以通过执行setTitleColor(.white, for: .normal)
来设置按钮的颜色,这会将按钮设置为白色。但是如果想检查按钮内标题的颜色呢?
我试过了
let color = titleColor(for: .normal)
和let color = titleLabel?.textColor
但是当我尝试在其他地方设置该颜色时,没有任何反应。
使用:
extension UIButton {
func loadingIndicator(show: Bool) {
let tag = 9876
var color: UIColor?
if show {
color = titleColor(for: .normal)
let indicator = UIActivityIndicatorView()
let buttonHeight = self.bounds.size.height
let buttonWidth = self.bounds.size.width
indicator.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2)
indicator.tag = tag
indicator.color = UIColor.white
setTitleColor(.clear, for: .normal)
self.addSubview(indicator)
indicator.startAnimating()
} else {
if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
indicator.stopAnimating()
indicator.removeFromSuperview()
setTitleColor(color, for: .normal)
}
}
}
}
答案 0 :(得分:0)
这就是您可以使用UIButton
获取state
标题的颜色,而不是在任何您想要的地方使用它。
let color = btn.titleColor(for: .normal);
label.textColor = color
正如您所见,此图像中的Label TextColor中正确使用了我的Button颜色。
这是你在扩展
中的方法extension UIButton {
func loadingIndicator(show: Bool) {
let tag = 9876
var color: UIColor?
if show {
color = titleColor(for: .normal)
let indicator = UIActivityIndicatorView()
let buttonHeight = self.bounds.size.height
let buttonWidth = self.bounds.size.width
indicator.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2)
indicator.tag = tag
indicator.color = UIColor.white
setTitleColor(.clear, for: .normal)
self.addSubview(indicator)
indicator.startAnimating()
} else {
if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
indicator.stopAnimating()
indicator.removeFromSuperview()
setTitleColor(color, for: .normal)
}
}
}
}
并使用它:
//This will set the saved color for `UIButton` title
btn.loadingIndicator(show: false)