Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton Subclass - Setting Properties?

I've created a Subclass of UIButton to give it a white 2px No Radii border, and now I'm trying to "globally" set it's font, font color, and background color depending on the button state.

The font does not set. Nor do the colors or the background colors. What's going on? Here's my code. I hope you can help :)

- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
    
    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]];
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if(self.state == UIControlStateHighlighted) {
        [self setBackgroundColor:[UIColor whiteColor]];
    }
    else {
        [self setBackgroundColor:[UIColor blackColor]];
    }
}
return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {

             [self.layer setMasksToBounds:YES];
[self.layer setBorderWidth:2.0];
[self.layer setCornerRadius:0.0];
[self.layer setBorderColor:[[UIColor colorWithWhite:1.0 alpha:1.0] CGColor]];
}

I don't think I'm doing anything wrong. I have this class, and have linked Buttons in IB, and set the class type.

like image 654
topLayoutGuide Avatar asked Oct 04 '11 07:10

topLayoutGuide


2 Answers

If you have created the custom subclass buttons in IB, initWithFrame: will not be called. You need to override initWithCoder:, or, preferably, create a separate setup method that is called both from initWithFrame: and initWithCoder:.

For the first case:

- (id)initWithCoder:(NSCoder*)coder {
self = [super initWithCoder:coder];
if (self) {

    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]];
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if(self.state == UIControlStateHighlighted) {
        [self setBackgroundColor:[UIColor whiteColor]];
    }
    else {
        [self setBackgroundColor:[UIColor blackColor]];
    }
}
return self;
}
like image 164
jrturton Avatar answered Nov 15 '22 20:11

jrturton


Here's how I do it (without IB):

+ (instancetype)customButtonWithCustomArgument:(id)customValue {
    XYZCustomButtom *customButton = [super buttonWithType:UIButtonTypeSystem];
    customButton.customProperty = customValue;
    [customButton customFunctionality];
    return customButton;
}

Works also with other types, UIButtonTypeSystem is just an example.

like image 37
Rudolf Adamkovič Avatar answered Nov 15 '22 19:11

Rudolf Adamkovič