iosiphonecocoa-touchuibuttonimageedgeinsets

iPhone UIButton - image position


I have a UIButton with text "Explore the app" and UIImage (>) In Interface Builder it looks like:

[ (>) Explore the app ]

But I need to place this UIImage AFTER the text:

[ Explore the app (>) ]

How can I move the UIImage to the right?


Solution

  • Here is my own way to do the thing, (after about 10 years)

    1. Subclass from UIButton (Button, as we're living in Swift era)
    2. Put an image and a label in a stack view.
    class CustomButton: Button {
    
        var didLayout: Bool = false // The code must be called only once
    
        override func layoutSubviews() {
            super.layoutSubviews()
            if !didLayout, let imageView = imageView, let titleLabel = titleLabel {
                didLayout = true
                let stack = UIStackView(arrangedSubviews: [titleLabel, imageView])
                addSubview(stack)
                stack.edgesToSuperview() // I use TinyConstraints library. You could handle the constraints directly
                stack.axis = .horizontal
            }
        }
    }