Search code examples
iosuibuttonsubclass

how to set UIButton type in UIButton Subclass


I am subclassing the UIButton, what i want is to set the button type to Round Rect.

Button.h

@interface Button : UIButton {}
    - (void)initialize;
@end

Button.m

@implementation Button

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}


-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self){
        [self initialize];
    }
    return self;
}

- (void)initialize
{
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textColor = [UIColor redColor];
    self.titleLabel.textAlignment = UITextAlignmentCenter;
   //[UIButton buttonWithType:UIButtonTypeRoundedRect];
}

@end

Here i tried [UIButton buttonWithType:UIButtonTypeRoundedRect] but it doesn't work. Can anyone suggest how to make it work?

I know in many previous post it has been said that Subclassing UIButton is not recommended, but the fact that in Developer's Docs there is no mention about NOT subclassing it.


Solution

  • You may find the discussion at CocoaBuilder's thread How to subclass UIButton? helpful, particularly Jack Nutting's suggestion to ignore the buttonType:

    Note that this way the buttonType isn't explicitly set to anything, which probably means that it's UIButtonTypeCustom. The Docs don't seem to actually specify that, but since that's the 0 value in the enum, that's likely what happens (and that seems to be the observable behavior as well)