UIButton Background Image Offset

Is there any way to add some kind of offset to the background image of UIButton ?

I have some custom background images for UIButton . These images have a 5 pixel shadow area around the effective area of โ€‹โ€‹the button. When I use these images, I need to move the title bar, adjust the frame and do some calculations to fit the buttons correctly.

Ideally, I would like to set something like offset (x = -5px, y = -5px) on this image (or UIButton ) so that when you assign the image as a background, the UIButton moves horizontally and vertically with this offset.

In html, I set a fixed size to the div button, and then offset the background image, indicating the background position.

Is there something similar for iOS?

+7
ios uibutton offset
source share
6 answers

The setTitleEdgeInsets: or setImageEdgeInsets: do not seem to affect the background image of the UIButton , but only the image (and title).

I ended up with an override -(CGRect)backgroundRectForBounds:(CGRect)bounds , where I inflated the border rectangle by the required amount (5 in my case).

+12
source share

This is an old question, but I think the answer might be better. One way to do this is to grab your button and then capture its image. So, if you configured your buttons in IB, it might look like this: objc:

UIImage *i = [self.button backgroundImageForState:UIControlStateNormal];

If you did this in code, then you already have these things!

And then you want to adjust the alignment to adjust the difference.

i = [i imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, -5, -5)];

(top, left, bottom, right).

Now set the button image.

 [self.button setBackgroundImage:i forState:UIControlStateNormal]; 

Auto Layout uses alignment rectangles to align. You may need to change some constants on your alignments to fine tune.

+10
source share

In the attribute inspector for UIbuton, you can set the title / image insert value.

enter image description here

+2
source share

You can play with both setTitleEdgeInsets: and setImageEdgeInsets: to get the desired result.

+1
source share

Just update SmileBot answer:

Create a button (in my case UIBarButtonItem) programmatically and set the background image with an offset (+2 px at the top edge):

Swift 3

 let image = UIImage(named: "yourimagename")!.withAlignmentRectInsets(UIEdgeInsetsMake(2, 0, 0, 0)) let button = UIButton(type: .custom) button.frame = CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height) button.setBackgroundImage(image, for: UIControlState()) 
+1
source share

Try this for bias

 [buttonName setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 12.0, 0.0, 0.0)]; 
0
source share

All Articles