Search code examples
xcodexcode8swift5

Set title color of all UIbuttons on button click


I set title color of button

button.setTitle("Print 0", for: UIControl.State.normal)

but I have many buttons how can I set it at once set radius and border working but set title have some issues

@objc extension UIButton {
    dynamic var borderColor: UIColor? {
        get {
            if let cgColor = layer.borderColor {
                return UIColor(cgColor: cgColor)
            }
            return nil
        }
        set { layer.borderColor = newValue?.cgColor }
    }

    dynamic var borderWidth: CGFloat {
        get { return layer.borderWidth }
        set { layer.borderWidth = newValue }
    }

    dynamic var cornerRadius: CGFloat {
        get { return layer.cornerRadius }
        set { layer.cornerRadius = newValue }
    }
      dynamic var setTitleColor: UIButton? {
        get {
            if let cgColor = layer.color {
                return UIColor(cgColor: cgColor)
            }
            return nil
        }
        set { layer.setTitleColor = newValue?.cgColor }
    }

}

Solution

  • Instead of layer.color, use titleColor(for:) and setTitleColor(, for:) like this:

    extension UIButton {
        dynamic var normalTitleColor: UIColor? {
            get {
                return titleColor(for: .normal)
            }
            set {
                setTitleColor(newValue, for: .normal)
            }
        }
    }