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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With