0

I need to put button image right after the text. Following some answers I found here on SoF, I have subclassed UIButton like the following:

class RightAlignedIconButton: UIButton {
    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        var frame = super.titleRect(forContentRect: contentRect)
        frame.origin.x = titleEdgeInsets.left

        return frame
    }

    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        let titleRectangle = titleRect(forContentRect: contentRect)

        var frame = super.imageRect(forContentRect: contentRect)
        frame.origin.x = titleRectangle.origin.x + titleRectangle.width + imageEdgeInsets.left

        return frame
    }
}

The problem I experience is that when I change text with acceptanceStatusButton.setTitle("New text", for: .normal) icon remains where it was despite text being longer/shorter (so sometimes I have icon right on top of new long text). How can I resolve this issue?

realvadim
  • 154
  • 12

1 Answers1

0

If you just use the standard setTitle and setImage, it will automatically include the image to the right of the title. You don't need a custom subclass.

//Set button's image
let image = UIImage(systemName: "heart.fill") //Your image here
button.setImage(image, for: .normal)

//Optional: Remove background image if you added one on accident
button.setBackgroundImage(nil, for: .normal)

//Optional: Set button's title (displayed next to button's image)
button.setTitle(nil, for: .normal)

//The button's "content" includes the title label and image
//So we can set the button's content to fill the button
//If title label is nil, the content will only show the image
button.contentVerticalAlignment = .fill //optional
button.contentHorizontalAlignment = .fill //optional

//Set button's image to desired content mode (aspectFit avoids distortion)
//This restricts the image from resizing to fill the entire content area
button.imageView?.contentMode = .scaleAspectFit
nicksarno
  • 3,850
  • 1
  • 13
  • 33