UIButton with image on the right side.

Alex Permiakov
2 min readApr 17, 2023

In case your app still supports iOS14 and you do not have a privilege to use UIButton.Configuration, then this article can come in handy if you are looking for a solution on how to place the image on the right side of button’s title.
By default imageView of UIButton located on the leading side, so we need a bit of extra effort to move it after the text like so:

UIButton with image on the right.

To make the code easy to use, let’s make an extension:

extension UIButton {
func swapImageAndTextWith(spacing: CGFloat) {
// TBC...
}

Let’s define properties in the function’s body to access width properties of image view and title.
Please note that we divided the spacing by 2. We would need it to enlarge the content of the button itself equally from both left and right.

let imageWidth = imageView?.frame.width ?? 0
let titleWidth = titleLabel?.frame.width ?? 0
let offset = spacing / 2

Next we need to shift the image to the right by the titleWidth + offset:

imageEdgeInsets = .init(top: 0,
left: titleWidth + offset,
bottom: 0,
right: -(titleWidth +offset))

Opposite we are going to do with the titleEdgeInsets and shift it left by the titleWidth + offset:

titleEdgeInsets = .init(top: 0,
left: -(imageWidth + offset),
bottom: 0,
right: imageWidth + offset)

And the last but not least, we need to add up the offset from both sides of contentEdgeInsets:

contentEdgeInsets = .init(top: 0,
left: offset,
bottom: 0,
right: offset)

And all extension is going to be like so:

extension UIButton {
func swapImageAndTextWith(spacing: CGFloat) {
let imageWidth = imageView?.frame.width ?? 0
let titleWidth = titleLabel?.frame.width ?? 0
let offset = spacing / 2

imageEdgeInsets = .init(top: 0,
left: titleWidth + offset,
bottom: 0,
right: -(titleWidth + offset))
titleEdgeInsets = .init(top: 0,
left: -(imageWidth + offset),
bottom: 0,
right: imageWidth + offset)
contentEdgeInsets = .init(top: 0,
left: offset,
bottom: 0,
right: offset)
}
}

Since we are using frames in the extension, we need to call this method when views already have their sizes.

override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
button.swapImageAndTextWith(spacing: 16)
}

And we are done!

With this extension method, you can easily add some visual interest to your buttons by swapping the positions of the image and text, and adjusting the spacing between them.

--

--