I have a button with a)Image and b)Background Image - all built in a storyboard. The image is popping out of button as background image has a different shape. I want to give the actual image (a) some padding from all sides so it can shrink back within the background image. I can't do it with insets as they only give padding to non-opposite sides, when same insets are set to opposite sides - image doesn't shrink. It would be great to know how it's done in storyboard and programmatically.
UIButton padding inside Image from all sides
You can make a parent view, then put the image in it, set the constraints of the image to have spacing of 16 (for example) with each edge of the superview. –
Georgianngeorgianna
Sorry if not clear from the question, Image is button image, not UIImageView, so how can you put constraints between button and image inside it if they are the same thing –
Wanyen
You don't need to. Just make a parent UIView, then add constraints between your UIButton and this new parent –
Georgianngeorgianna
You can, select your UIButton, then use the Editor > Embed In > View , the set the constraints between your button and its newly created parent. Then set the parent's constraints –
Georgianngeorgianna
I think you are not getting the point. If i set constraints it would be to the edge of button - not image inside it. I want my background image to stay the same, but shrink the Button Image –
Wanyen
Got your point now and the answer must have screenshots –
Georgianngeorgianna
You can the UIView solution, how? make a UIView, put a UIImage inside it, and fill, then put the UIButton, set the constraints like you want. –
Georgianngeorgianna
It's not a simple button, there is a lot more to it - formatting when button clicked also reflected in image, so hoping for a solution –
Wanyen
You should set the button to fill the image. Doing so lets you use the image insets as padding. Note that this will stretch the image, so you need to pad properly on left/right vs top/bottom if you want a correct aspect ratio right.
In Storyboard you do this in the buttons control section. Then adjust the button's image insets.
In code you do like this.
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
And For iOS 15+
// 1. Create configuration for your button
var configuration = UIButton.Configuration.plain() // there are several options to choose from instead of .plain()
// 2. Here is your content Insets
configuration.contentInsets = NSDirectionalEdgeInsets(top: 24, leading: 24, bottom: 24, trailing: 24)
// 3. This is my Button and you can set to your Button the configuration
myButton.configuration = configuration
// 4. Hehe this step is just for fun, Swift is fun <3
ps.
it does not exit for old iOS versions, it is for only 15+
© 2022 - 2025 — McMap. All rights reserved.