开发者

UIButton Subclass - Setting Properties?

开发者 https://www.devze.com 2023-04-10 05:05 出处:网络
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.

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 i开发者_如何学运维mplementation 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.


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;
}


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.


UIButton is a class cluster. You really shouldn't be subclassing as the classes it represents are private.

0

精彩评论

暂无评论...
验证码 换一张
取 消