How to write a Custom UILabel Class

有些话、适合烂在心里 提交于 2019-12-12 17:15:11

问题


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

回答1:


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;
}



回答2:


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


来源:https://stackoverflow.com/questions/34586506/how-to-write-a-custom-uilabel-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!