How to write a Custom UILabel Class

2019-07-19 17:00发布

In my project there is a huge number of UILabels available for each screen that's why I have created one separate class for UILabel and I want to set all label properties in that class.

But label properties and label also not adding in my MainViewController.

My code:

CustomLabel:

#import "CustomLabel.h"

@implementation CustomLabel

- (id) init {
    self = [super init];
    if(self){

        [self setupUI];
    }
    return self;
}

- (void)setupUI {

    [self setBackgroundColor:[UIColor redColor]];
    [self setTextColor:[UIColor blackColor]];
}

MainViewController:

#import "MainViewController.h"
#import "CustomLabel.h"

@interface MainViewController ()
{
    CustomLabel * mainLabel;
}

@end

@implementation SampleViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    mainLabel = [[CustomLabel alloc]initWithFrame:CGRectMake(50, 150, 100, 35)];
    [self.view addSubview:mainLabel];
}

@end

2条回答
2楼-- · 2019-07-19 17:38

awakeFromNib doesnt get called if you just alloc/init it yourself afaik, you need to put that [self setupUI]; in the init method that you should override

- (id) initWithFrame:(CGRect)frame {
   self = [super initWithFrame:frame];
   if(self){

      [self setupUI];
   }
   return self;
}
查看更多
冷血范
3楼-- · 2019-07-19 17:38

your label added successfully if you want to check then set some text for that.

i think you dont set any View for that label so awakeFromNib not call here for that you have to write code in layoutSubviews methods

#import "CustomLabel.h"

@implementation CustomLabel

-(void)layoutSubviews
{
    [self setupUI];
}

- (void)setupUI {

    [self setBackgroundColor:[UIColor redColor]];
    [self setTextColor:[UIColor blackColor]];
}

@end
查看更多
登录 后发表回答