简体   繁体   English

如何在iOS中制作自定义UILabel

[英]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. 在这里,我的主要要求是某些标签的颜色为白色,某些标签的文本颜色为黑色,但颜色不适用。

CustomUILabel class:- 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

Main class:- 主分类:-

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM