Home > database >  Custom UIButton imageEdgeInsets/titleEdgeInsets not working
Custom UIButton imageEdgeInsets/titleEdgeInsets not working

Time:02-17

The imegEdgeInsets and titleEdgeInsets are not working for my custom UIButton class. I'm setting the insets via nib

enter image description here

enter image description here.

Custom UIButton class code

class FilledButton: kButton {
    private var bgColor = AppTonalPalette.color(.primary)
    private var bgColorPressed = AppTonalPalette.color(.primary).withAlphaComponent(0.88)
    private var foregroundColor = AppTonalPalette.color(.onPrimary)
    
    private var bgColorDisabled = UIColor.init("#1F1F1F", alpha: 0.12)
    private var foregroundColorDisabled = AppTonalPalette.color(.onSurface)
    
    override func layoutSubviews() {
        super.layoutSubviews()
        updateViews()
    }
    
    func updateViews() {
        tintColor = isEnabled ? foregroundColor : foregroundColorDisabled
        setTitleColor(isEnabled ? foregroundColor : foregroundColorDisabled, for: .normal)
        setTitleColor(isEnabled ? foregroundColor : foregroundColorDisabled, for: .highlighted)
        backgroundColor = isEnabled ? (isHighlighted ? bgColorPressed : bgColor) : bgColorDisabled
    }
}

class kButton: UIButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        setup()
    }
    
    func setup() {
        titleLabel?.font = AppFont.fontOf(size: 14, style: .Regular)
        setNeedsLayout()
    }
}

I've also tried adding insets in mu custom class code like:

    func updateViews() {
        tintColor = isEnabled ? foregroundColor : foregroundColorDisabled
        setTitleColor(isEnabled ? foregroundColor : foregroundColorDisabled, for: .normal)
        setTitleColor(isEnabled ? foregroundColor : foregroundColorDisabled, for: .highlighted)
        backgroundColor = isEnabled ? (isHighlighted ? bgColorPressed : bgColor) : bgColorDisabled
        
        if imageView?.image != nil {
            imageEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: 10)
            titleEdgeInsets = .init(top: 0, left: 10, bottom: 0, right: 0)
        }
    }

But still the same. What is missing here?

CodePudding user response:

Try changing button style to default via buttons attribute inspector.

enter image description here

  • Related