我有一个标签,我想在很少的地方使用它。它只有以下自定义设置
label.font = [UIFont fontWithName:@"Arial" size:12.0];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.userInteractionEnabled = YES;
label.textColor = [UIColor whiteColor];
现在我想知道,我是否需要专门为它引入一个子类(UILabel)?由于它在多个地方使用,这种用法的最佳设计模式是什么?
答案 0 :(得分:2)
@interface UILabel (MyLabel)
+ (UILabel *)createMyLabelWithFrame;
@end
和.m:
@implementation UILabel (MyLabel)
+ (UILabel *)createMyLabelWithFrame:(CGRect)frame {
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.font = [UIFont fontWithName:@"Arial" size:12.0];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.userInteractionEnabled = YES;
label.textColor = [UIColor whiteColor];
return label;
}
答案 1 :(得分:1)
我会在某个可用类上使用类别或基本函数。子类化创造了更多的工作。即不断更改IB中的类或更改整个项目中的所有代码。
类别可能如下所示:
@implementation UILabel (FormatMyLabels)
-(void)useMySpecialFormatting{
self.font = [UIFont fontWithName:@"Arial" size:12.0];
self.textAlignment = UITextAlignmentCenter;
self.backgroundColor = [UIColor clearColor];
self.userInteractionEnabled = YES;
self.textColor = [UIColor whiteColor];
}
@end
你会像以下一样使用它:
[self.myFirstLabel useMySpecialFormatting];
功能可能如下所示:
-(void)useSpecialFormattingOnLabel:(UILabel *)label{
label.font = [UIFont fontWithName:@"Arial" size:12.0];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.userInteractionEnabled = YES;
label.textColor = [UIColor whiteColor];
}
你可以使用它:
[ClassOrInstanceWithFunction useSpecialFormattingOnLabel:self.myFirstLabel];