找出uibutton里面标题的颜色

时间:2017-05-22 16:51:27

标签: swift uibutton

您可以通过执行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)
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

这就是您可以使用UIButton获取state标题的颜色,而不是在任何您想要的地方使用它。

let color = btn.titleColor(for: .normal);
label.textColor = color

正如您所见,此图像中的Label TextColor中正确使用了我的Button颜色。 enter image description here

这是你在扩展

中的方法
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)