Extending(Subclassing) UIButton in Objective-C

Friday, July 10th, 2009

After playing around with UIButton class for a while I found Apple have been very sneaky with some  of their UI classes.

What it appears they have done is use the UIButton class as a sort of wrapper for a number of private button classes. “UIRoundedRectButton” is one of those classes.

“UIRoundedRectButton” is a private class so it can not be extended(subclassed). The initilizers normaly return an instance of self and if that self is not the class type trying to hold it there will be trouble. The problem is if you initialise UIButton with buttonWithType the class it returns is a private class. If you try and extended the UIButton once your custom class is initialized it returns a “UIRoundedRectButton” object which is private so you can not contain it.

If you try the code below which uses the description you can see the object description is not UIButton.

In short you can not extend UIButton and initialize it with buttonWithType  in Objective C. On the other hand you can extened UIButton for a button in interface builder. If  you use interface builder you need to use initWithCoder as the initialiser. While interface builder does the private stuff.

4 comments on “Extending(Subclassing) UIButton in Objective-C

  1. Dennis says:

    Thanks Abe. Knowing this in advance will save me a lot of time 🙂

  2. abe says:

    ya its a pain took me while before i found out too 🙂

  3. Trevor says:

    I think you are wrong about this. See:

    http://supergravelynbros.com/?p=871

    I have used this technique myself without any problems.

  4. abe says:

    Aaah yes you are right this will allow you to create a button using images…but as far as extending or building on the current apple component set that is not possible becuase of the inability to use buttonWithType which alwasy returns a private class.

Leave a Reply

Your email address will not be published. Required fields are marked *