Swift Tutorials: Aligning text and image on UIButton

UIEdgeInsets are handy when it comes to give padding to title of UIButton having image or in other words when we need aligning text and image on UIButton. According to Apple docs UIEdgeinset

Edge inset values are applied to a rectangle to shrink or expand the area represented by that rectangle. Typically, edge insets are used during view layout to modify the view’s frame. Positive values cause the frame to be inset (or shrunk) by the specified amount. Negative values cause the frame to be outset (or expanded) by the specified amount.

Apple iOS Documentation

In this tutorial, we will learn about 3 types of UIEdgeinsets by taking an example of UIButton

  • titleEdgeInsets: adding padding to title label rectangle
  • imageEdgeInsets: adding padding to UIImageview
  • contentEdgeInsets: adding padding to rectangle containing title and image

Aligning text and image on UIButton

Before digging further, we are assuming that you have a UIButton with image added to it and title of UIButton is set as shown in below image

Swift Tutorials: Aligning text and image on UIButton
UIButton having image and title

Adding padding using titleEdgeInsets

btnFruits.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: -10)
UIButton after applying titleEdgeInsets
UIButton after applying titleEdgeInsets

After applying titleEdgeInsets, our UIButton title is going out of UIButton rectangle. To fix this we can use contentEdgeInsets, as it takes of UIButton rectangle.

btnFruits.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
UIButton after applying contentEdgeInsets
UIButton after applying contentEdgeInsets

Adding padding using imageEdgeInsets

If you don’t want to use titleEdgeInsets, one can use imageEdgeInsets as shown below

btnFruits.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)
Swift Tutorials: Aligning text and image on UIButton
UIButton after applying imageEdgeInsets

Watch video on YouTube: https://youtu.be/dmg9OLzrK_4

Where to go from here

In this small tutorial, we learned how to Aligning text and image on UIButton with help of UIEdgeInsets in swift, or how to add padding to UIImage and title of UIButton using UIEdgeInsets, mainly titleEdgeInsets, contentEdgeInsets, imageEdgeInsets.

1 thought on “Swift Tutorials: Aligning text and image on UIButton”

Comments are closed.