Phan Van Linh Phan Van Linh - 1 month ago 11
Objective-C Question

Should I override a property in child class form parent class (UIButton)

I want to create a custom button, that will help me change all button background color to default red color if I don't set any color for the button.

So I do like this and it working well

in .h file I have

@interface ITSButton : UIButton
@property(nonatomic, strong) UIColor *backgroundColor;
@property(nonatomic, strong) UIColor *onPressBackgroundColor;
@end


in .m fie

-(UIColor *)backgroundColor
{
if(!_backgroundColor){
_backgroundColor = [UIColor redColor];
}
return _backgroundColor;
}


But the problem here
backgroundColor
is already a property of
UIButton
class. Is it good and clear if I override it in
ITSButton
?

And if I don't override
backgroundColor
property, I can not use the function
(UIColor *)backgroundColor
, so I can not set the default background to red

Answer

And if I don't override backgroundColor property, I can not use the function (UIColor*)backgroundColor, so I can not set the default background to red

Yes you can, and I think that realizing this is probably the key to your dilemma. Leave backgroundColor alone! It has an important job to do. Instead, implement the initializer of your subclass to set the background color of this button to red. You should do this for all possible initializers; the two most likely are initWithFrame: and initWithCoder:.

The result is that all buttons of this class, and all buttons of any subclass of this class, will be red by default, which is what you want. And to change that, you just set the background color of the button, just as you do now with any button.

Don't forget to read the docs on how to override an initializer in a subclass if you don't already know the rules on how to do it.

Comments