10

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?

Mirko Catalano
  • 3,850
  • 2
  • 26
  • 39
gabelkonus
  • 466
  • 1
  • 4
  • 13

6 Answers6

20

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).

gabelkonus
  • 466
  • 1
  • 4
  • 13
13

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.

SmileBot
  • 19,393
  • 7
  • 65
  • 62
2

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())
Jorge Ramírez
  • 657
  • 1
  • 7
  • 8
1

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

enter image description here

Rocker
  • 1,269
  • 7
  • 15
1

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

Rom.
  • 2,800
  • 2
  • 17
  • 19
0

Try this for offset

[buttonName setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 12.0, 0.0, 0.0)];
Indra
  • 528
  • 2
  • 11