在我的项目中有大量的UIlabel
。我为 UILabel
创建了一个单独的自定义类,并在该类中设置了所有标签的属性。
这里我的主要要求是一些标签的颜色是白色,一些标签的文本颜色是黑色,但颜色不适用。
CustomUILabel 类:-
#import "CustomLabel.h"
@implementation CustomLabel
-(void)layoutSubviews{
[self setupUI];
}
- (void)setupUI {
[self setTextAlignment:NSTextAlignmentLeft];
[self setFont:[UIFont fontWithName:@"Futura" size:14.0]];
[self setBackgroundColor:[UIColor clearColor]];
[self setTextColor:[UIColor blackColor]];
}
@end
主类:-
#import "MainViewController.h"
@interface MainViewController (){
}
@end
@implementation MainViewController
@synthesize label1,label2;
- (void)viewDidLoad {
[super viewDidLoad];
label1.textColor = [UIColor whiteColor];
label2.textColor = [UIColor blackColor];
}
最佳答案
当你覆盖layoutSubviews
时,你必须调用[super layoutSubviews]
。但这不是你的问题。问题是您在 layoutSubviews
中调用 setupUI
,而您不应该这样做。布局发生在 viewDidLoad
之后,因此当 setupUI
运行时,您在 viewDidLoad
中设置颜色的尝试将在稍后的布局期间被覆盖。
您应该从子类的初始化方法中调用 setupUI
:
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setupUI];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self setupUI];
}
return self;
}
而且您根本不应该在 CustomLabel
中覆盖 layoutSubviews
。
关于ios - 如何在 ios 中制作自定义 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34626410/