How do you make a UIButton with no text be the size of its image?

Viewed 425

I created a UIButton in Interface Builder that consists of only an SF Symbol and no text. The button draws with insets around the image, which affects how it's positioned with constraints. How do I remove that extra space, so that the button view is just the size of the SF Symbol image?

enter image description here

1 Answers

Button with the intrinsic size of the Image

Image

A button will take the size of the image by default. but since SF-Symbols are vectors, they can be scaled to any size. Each symbol has a few predefined sizes that you can choose:

predefined Sizes

Also, you can set your own size in the code:

let config = UIImage.SymbolConfiguration(pointSize: 160, weight: .bold, scale: .large)
       
let largeChevronImage = UIImage(systemName: "chevron.right.circle.fill", withConfiguration: config)

button.setImage(largeChevronImage, for: .normal)

Add or Remove Extra space around the image

Some images and SF-Symbols have some paddings around their content. You can control the size of the padding by setting the ContentEdgeInsets

Offset

You can clip the bounds to hide the out of frame content

All SF-Symbols have same size

Related