3

If I have a UIButton and give it a red background, and the background size is a little too small or too big for my liking (but the tap target size is perfect), is there any way to change the size of them?
Basically the equivalent of adding padding in CSS so that it either takes up more area or less? Purely an aesthetic change.

Say with the background color applied to the button it visually takes up a 100px * 30px area. I want it to be 90px * 25px. Is this possible?

S1LENT WARRIOR
  • 11,704
  • 4
  • 46
  • 60
Doug Smith
  • 29,668
  • 57
  • 204
  • 388

1 Answers1

3

One way to do this, is to set the color of a sublayer of the button rather than the background color of the button itself.

- (void)viewDidLoad {
    [super viewDidLoad];
    CALayer *sub = [CALayer new];
    sub.frame = CGRectInset(self.topButton.bounds, 5, 2.5); // this will make the layer 90x25 for a button that is 100x30
    sub.backgroundColor = [UIColor redColor].CGColor;
    [self.topButton.layer addSublayer:sub];
}
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Where is it recommended to do this? I use the button in many places, so doing it in the `viewDidLoad` of every VC wouldn't work well. Is it still dangerous to subclass `UIButton`? – Doug Smith Oct 10 '14 at 03:36
  • @DougSmith, you can do it wherever you want, and it's ok to subclass a button. – rdelmar Oct 10 '14 at 03:47
  • Is this not the case anymore? http://stackoverflow.com/questions/13202161/why-shouldnt-i-subclass-a-uibutton – Doug Smith Oct 10 '14 at 21:30
  • 1
    @DougSmith, I see several different opinions in the answers to that question. I think as long as you're just doing what I have in my code, not trying to create a new type of button, you'll be fine. – rdelmar Oct 10 '14 at 23:22
  • Fair enough. When I implement this solution, however, the background doesn't seem to properly fit to the button, it's offset oddly. Here's an example project: http://cl.ly/1d3H3n0v2729 – Doug Smith Oct 11 '14 at 02:34
  • @DougSmith, that's because your button is the custom type. If you make it the default system type, it works fine. If you look at the buttonWithType: description in the docs, it says that the custom button initially has a frame of {{0,0},{0,0}}. This must be screwing things up. I found out that it works with a custom button if I put your code in updateConstraints instead of awakeFromNib – rdelmar Oct 11 '14 at 04:13