5

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?

RJ168
  • 1,006
  • 2
  • 12
  • 22
Raj D
  • 205
  • 3
  • 16
  • What exactly you want to achieve? I tried your insets on a standard UIButton with an image – it looks as yours. Take a look at this discussion: https://stackoverflow.com/questions/4564621/aligning-text-and-image-on-uibutton-with-imageedgeinsets-and-titleedgeinsets It might be helpful for understanding how to achieve different insets in cases like yours. – lazarevzubov Feb 16 '22 at 07:02
  • @lazarevzubov I want some space between title and image – Raj D Feb 16 '22 at 07:12

1 Answers1

12

Try changing button style to default via buttons attribute inspector.

enter image description here

Tal Sahar
  • 784
  • 1
  • 7
  • 10