如何编写自定义 UILabel Class
How to write a Custom UILabel Class
在我的项目中,每个屏幕都有大量 UILabels
可用,这就是为什么我为 UILabel
创建了一个单独的 class 并且我想在中设置所有标签属性class.
但是标签属性和标签也没有添加到我的MainViewController
。
我的代码:
自定义标签:
#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]];
}
主视图控制器:
#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
awakeFromNib
如果你只是 alloc/init 它自己 afaik,则不会被调用,你需要将 [self setupUI];
放在你应该覆盖的 init 方法中
- (id) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self){
[self setupUI];
}
return self;
}
你的标签添加成功,如果你想检查然后设置一些文本。
我认为您没有为该标签设置任何视图,所以 awakeFromNib 不要在这里调用
为此,您必须在 layoutSubviews 方法中编写代码
#import "CustomLabel.h"
@implementation CustomLabel
-(void)layoutSubviews
{
[self setupUI];
}
- (void)setupUI {
[self setBackgroundColor:[UIColor redColor]];
[self setTextColor:[UIColor blackColor]];
}
@end
在我的项目中,每个屏幕都有大量 UILabels
可用,这就是为什么我为 UILabel
创建了一个单独的 class 并且我想在中设置所有标签属性class.
但是标签属性和标签也没有添加到我的MainViewController
。
我的代码:
自定义标签:
#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]];
}
主视图控制器:
#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
awakeFromNib
如果你只是 alloc/init 它自己 afaik,则不会被调用,你需要将 [self setupUI];
放在你应该覆盖的 init 方法中
- (id) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self){
[self setupUI];
}
return self;
}
你的标签添加成功,如果你想检查然后设置一些文本。
我认为您没有为该标签设置任何视图,所以 awakeFromNib 不要在这里调用 为此,您必须在 layoutSubviews 方法中编写代码
#import "CustomLabel.h"
@implementation CustomLabel
-(void)layoutSubviews
{
[self setupUI];
}
- (void)setupUI {
[self setBackgroundColor:[UIColor redColor]];
[self setTextColor:[UIColor blackColor]];
}
@end