gabelkonus
gabelkonus

Reputation: 466

UIButton background image offset

Is there a way to add some sort of offset to UIButton's background image?

I've got some custom background images for UIButton. These images do have a 5 pixel drop shadow area around the effective button area. When I use these images I have to move the title label around, adjust the frame and do some calculations to place the buttons correctly.

Ideally, I would like to set something like an offset (x = -5px, y = -5px) on that image (or the UIButton) so that when I assign the image as a background to the UIButton it is moved by that offset horizontally and vertically.

In html I would set a fixed size on the button div and then offset the background image by specifying background-position.

Is there something similar for iOS?

Upvotes: 10

Views: 12286

Answers (6)

Jorge Ramírez
Jorge Ramírez

Reputation: 683

Just updating SmileBot answer:

Create a button (in my case an UIBarButtonItem) programatically and set its background image with offset (+2 px in 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())

Upvotes: 2

SmileBot
SmileBot

Reputation: 19642

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

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

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

And then you want to setup your alignment rect to adjust for the difference.

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

(top, left, bottom, right).

Now set the button image back.

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

Auto layout uses alignment rects to line things up. You might have to change some constants on your alignments to fine tune.

Upvotes: 13

gabelkonus
gabelkonus

Reputation: 466

Setting setTitleEdgeInsets: or setImageEdgeInsets: do not seem to have any effect on the background image of an UIButton but only on the image (and the title).

I ended up with overriding -(CGRect)backgroundRectForBounds:(CGRect)bounds where I inflate the bounds rectangle by the amount needed (5 in my case).

Upvotes: 20

Rom.
Rom.

Reputation: 2830

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

Upvotes: 1

Rocker
Rocker

Reputation: 1269

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

enter image description here

Upvotes: 1

Indra
Indra

Reputation: 548

Try this for offset

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

Upvotes: 0

Related Questions