我正在子类化UILabel
in a CustomLabel class
。当我尝试使用简单的方法时遇到问题UILabel
我希望将来对其他元素进行子类化。我读到我可以创建一个category
of UILabel
。这东西哪一个比较好呢?类别还是子类?
这是我尝试子类化的代码。它失败于setFont
method.
@interface WPCustomLabel : UILabel
@property (strong, nonatomic) UIColor *color;
@property (strong, nonatomic) UIFont *font;
@end
#import "WPCustomLabel.h"
@implementation WPCustomLabel
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor clearColor]];
}
return self;
}
-(void)setColor:(UIColor *)color
{
self.color = color;
}
-(void)setFont:(UIFont *)font
{
self.font = font;
}
@end
我在 ViewController 中将此称为 CustomLabel。
@property (strong, nonatomic) WPCustomLabel *titleLbl;
titleLbl = [[WPCustomLabel alloc] initWithFrame:CGRectMake(75, 25, 200, 14)];
[titleLbl setTextColor:[UIColor blackColor]];
[titleLbl setFont:[UIFont systemFontOfSize:14]];
[titleLbl setBackgroundColor:[UIColor clearColor]];
[titleLbl setText:@"Here I AM"];
[self.view addSubview:titleLbl];
如何子类化 UILabel、UIButton 等 UI 元素
绝不。
我读到我可以创建一个类别UILabel
这是正确的。事实上,如果你想extend类,您可能应该使用类别来代替(请参阅前面的答案)。
setFont 方法失败。
您没有说明它是如何“失败”的,但我只能猜测它会导致无限递归并因此导致堆栈溢出/分段错误。那是因为
self.font = font;
相当于
[self setFont:font];
因此,您无条件地从自身内部调用该方法。
如果您不需要自定义这些属性的行为,则无需理会它们。 :)如果你这样做,然后完成后调用超类的实现:
- (void)setFont:(UIFont *)font
{
[self doScaryCustomMagicStuff];
[super setFont:font];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)