[英]How to make Custom UILabel in ios
In my project there is huge number of UIlabel
s. 在我的项目中,有大量的
UIlabel
。 I have created one separate custom class for UILabel
and I have set all label's properties in that class. 我为
UILabel
创建了一个单独的自定义类,并在该类中设置了所有标签的属性。
Here my main requirement is some labels' color is white and some labels' text color is black but color is not applying. 在这里,我的主要要求是某些标签的颜色为白色,某些标签的文本颜色为黑色,但颜色不适用。
#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];
}
When you override layoutSubviews
, you must call [super layoutSubviews]
. 覆盖
layoutSubviews
,必须调用[super layoutSubviews]
。 But that's not your problem here. 但这不是您的问题。 The problem is that you're calling
setupUI
in layoutSubviews
, and you shouldn't. 问题在于您正在
layoutSubviews
调用setupUI
,而不应该这样做。 Layout happens after viewDidLoad
, so your attempt to set the color in viewDidLoad
gets overridden later during layout, when setupUI
runs. 布局发生在
viewDidLoad
之后,因此稍后在运行setupUI
时,在布局期间覆盖您在viewDidLoad
设置颜色的尝试。
You should be calling setupUI
from the init methods of your subclass: 您应该从子类的init方法调用
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;
}
And you shouldn't override layoutSubviews
at all in CustomLabel
. 而且,您不应该在
CustomLabel
完全覆盖layoutSubviews
。
The problem is with your layoutSubview
method and your setupUI
method. 问题出在您的
layoutSubview
方法和setupUI
方法上。
layoutSubviews
is not the proper place to call setupUI
. layoutSubviews
不是调用setupUI
的适当位置。 layoutSubviews
can be called many times and is most likely being called a couple of times after viewDidLoad
is called which is why the colors are being reset back to black. layoutSubviews
可以被调用很多次,并且最有可能在调用viewDidLoad
之后被调用了两次,这就是为什么将颜色重新设置为黑色的原因。
And always call [super layoutSubviews];
并始终调用
[super layoutSubviews];
in your layoutSubviews
method. 在您的
layoutSubviews
方法中。
The better place to call your setupUI
method is from one or more of the appropriate init...
methods and possibly awakeFromNib
. 调用
setupUI
方法的更好位置是来自一个或多个适当的init...
方法,还有可能是awakeFromNib
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.