1

I made a subclass of UIButton, and I want to set a "padding". I want the button's frame to always be 15 pixels wider on each side, than the text.

In the drawRect method, I set the frame of the button to be 30 px wider than the text's width. But when I try to do this the frame does not get adjusted at all. Is this frame getting adjusted after I change the frame of my uibutton? How can I adjust the frame to set a padding?

Here is my code:

- (void)drawRect:(CGRect)rect{
[self setBackgroundImage:[[UIImage imageNamed:@"submitBtn.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0] forState:UIControlStateNormal];
[self setFrame:CGRectMake(rect.origin.x, rect.origin.y-90, self.titleLabel.frame.size.width + 30, self.frame.size.height)]; 
}

Thanks for the answers!!

SirRupertIII
  • 12,324
  • 20
  • 72
  • 121

1 Answers1

2

You should override the setTitle:forState: method and adjust the frame there. You should also set the background image somewhere other than drawRect:. A good place would be the initXXX method.

The only thing you should do in drawRect: is actually render content for the view based on its current state. No state should be changed in drawRect:.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks, this is my first time subclassing this way so I am trying to learn the basics. I used drawRect: because it was the only method that I found that gets called. I tried using the initWithFrame: method, it doesn't get fired for some reason. – SirRupertIII Nov 01 '12 at 22:04
  • What `initXXX` method are you calling to create the button? Override that one. – rmaddy Nov 01 '12 at 22:06
  • I just dragged the button onto my .xib file and changed the class to my uibutton subclass – SirRupertIII Nov 01 '12 at 22:12
  • I don't use IB so I can't help with that aspect. Sorry. – rmaddy Nov 01 '12 at 22:14
  • Oh, I actually just found it. The initWithCoder method gets called. – SirRupertIII Nov 01 '12 at 22:17
  • Dang, it doesn't change when I put setFrame: in that method either. – SirRupertIII Nov 01 '12 at 22:17
  • 1
    Try the `initWithCoder:` method. That might be called when created from a xib. Edit: Oops - I missed your previous message. – rmaddy Nov 01 '12 at 22:19
  • Okay, thanks for the answer, you answered it, I just found out that my setFrame was doing nothing because I am using autolayout. I'll ask another question about that. – SirRupertIII Nov 01 '12 at 23:12
  • http://stackoverflow.com/questions/13186908/can-i-use-setframe-and-autlayout-on-the-same-view Here is my other question – SirRupertIII Nov 01 '12 at 23:12