1

How do I draw the title of a UIButton when subclassing it? I need to subclass the UIButton class because of a custom drawRect method for drawing the button.

I believe that I have to draw the title inside the drawRect method, do I see that correctly?

jrturton
  • 118,105
  • 32
  • 252
  • 268
c2programming
  • 235
  • 3
  • 17
  • Or just call `[super drawRect:]`... –  Dec 11 '12 at 20:02
  • 2
    Please have a look at http://stackoverflow.com/questions/6443639/objective-c-buttons-created-from-subclass-of-uibutton-class-not-working – it is quite tricky to subclass a UIButton to override drawing. – Anton Dec 11 '12 at 20:02
  • whats the ‘[super drawRect:]‘ method suppose to do? is it suppose to draw the title? (Of course i set the title with ‘self.titleLabel.text = titleName‘ – c2programming Dec 11 '12 at 20:13
  • @ChristopherScottyWittlinger [super drawRect:] is the drawRect behaviour of the (non-subclassed) UIButton class, so since the normal UIButton draws the title for you, that functionality would be in [super drawRect:] – yuf Dec 11 '12 at 20:21
  • @yuf a button is composed of several views, the text isn't necessarily drawn by drawRect. – jrturton Dec 11 '12 at 20:31
  • if its not done by `[super drawRect:]` what do I have to do? I tried everything... – c2programming Dec 11 '12 at 20:38
  • @jrturton I see, I was just trying to explaining why that would be something to try. – yuf Dec 11 '12 at 20:52

1 Answers1

1

It is better (and advised by Apple) not to subclass UIButton if you can. Most custom appearances can be achieved by setting a background image to a standard "custom" button. This way you still get the functionality of resizing, the label, the image etc. without needing to subclass. A button has a background image, an image and a title label - how and by what these components are drawn is not publicly available.

If the image is derived at run time, you can still use the above technique, but draw in a new graphics context, extract the image and use that instead.

If you really must use a drawRect method, I'd subclass UIControl rather than UIButton.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • Okay so I should do the custom drawings in a UIImage and then set this as the background? – c2programming Dec 11 '12 at 20:45
  • I have written about something very similar here : http://commandshift.co.uk/blog/2012/12/09/subtle-ui-texture-in-code/ – jrturton Dec 11 '12 at 20:56
  • `It is better (and advised by Apple) not to subclass UIButton` - can you show any place where they are saying something like that? Even I would say that there are some small tips for subclassing in UIButton documentation. – lupatus Dec 11 '12 at 21:52
  • @lupatus it was mentioned on one of the WWDC 2012 videos, I can't remember which one though. – jrturton Dec 12 '12 at 08:46