UIButton Subclass - Setting Properties?
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.