Setting the imageEdgeInsets sets the spacing between the top, bottom, left, and right sides of the button icon. Similarly, titleEdgeInsets change the spacing between the sides of the title. I didn’t know these two attributes before, and I wrote a button to dynamically adjust the spacing.

By default, the spacing between image and title is zero, and the two are centered horizontally and vertically. ImageEdgeInsets and titleEdgeInsets are UIEdgeInsetsZero.

Left > 0, left margin increases, right shift, <0, left shift. Top > 0, the top distance increases, moves down, < 0, moves up. Right > 0, right margin increases, left shift, < 0, right shift. So bottom is greater than 0, so it goes up, < 0, it goes down.

In this way, we can adjust the orientation by controlling inset.

First let’s define an enumeration that defines the position of the image.

// Image position enum ButtonImagePosition: Int { case ButtonImageLeft = 0 case ButtonImageRight case ButtonImageTop case ButtonImageBottom }Copy the code

ButtonImageLeft

The default is ButtonImageLeft.

imageLeft.png

ButtonImageRight

If you want to move the image to the right, as shown below, you can see. The left spacing of image increases labelWidth, the right spacing of image decreases labelWidth, the left spacing of label decreases imageWidth, and the right spacing of label increases imageWidth.

Bottom = -top imageLeft = labelWidth imageRight = -labelWidth

labelLeft = -imageWidth

labelRight = imageWidth

imageRight.png

ButtonImageTop

Move image to the top.

newImageY = (buttonHeight – (labelHeight + imageHeight)) / 2

// new

imageLeft = (buttonWidth – imageWidth) / 2 – (buttonWidth – (labelWidth + imageWidth) / 2) => (labelWidth / 2)

// newImageY – oldImageY

imageTop = newImageY – (buttonHeight – imageHeight) / 2 => (-labelHeight / 2)

labelLeft = (buttonWidth – (labelWidth + imageWidth) / 2) – (buttonWidth – labelWidth) / 2 => (-imageWidth / 2)

labelTop = newImageY + imageHeight – (buttonHeight – labelHeight) / 2 => (imageHeight / 2)

Similarly, we can figure out the left and top of the label.

imageTop.png

ButtonImageBottom

Move image below. See ButtonImageTop.

imageBottom.png

Add a space

If we want to set the spacing between image and title, that’s easy. +/-space*0.5 will do the job. Such as space = 5,

ButtonImageTop: imageTop = -labelHeight / 2-space / 2

I wrote a button extension code at github.com/silan-liu/b…