ios - 如何编写自定义 UILabel 类

标签 ios objective-c uilabel

在我的项目中,每个屏幕都有大量的 UILabels 可用,这就是为什么我为 UILabel 创建了一个单独的类,并且我想在其中设置所有标签属性那个类(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]];
}

主视图 Controller :

#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 如果您自己分配/初始化它,则不会被调用,据我所知,您需要将 [self setupUI]; 放在您应该覆盖的 init 方法中

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

      [self setupUI];
   }
   return self;
}

关于ios - 如何编写自定义 UILabel 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34586506/

相关文章:

objective-c - NSFileManager createDirectoryAtPath :withIntermediateDirectories: Not creating directories or creating errors

ios - X 和 Y 值未应用于标签

ios - 将分布在屏幕边缘的可移动 UILabel 保存到有序数组中

ios - 如何将 segue 连接到不是第一个单元格的单元格上的披露指示器?

ios - 寻找用于创建复杂 UIBezierPath 的工具

ios - 在iOS设备上更改HTML5音频标题

ios - 无法从 facebook、ios 获取电子邮件。始终获取 null

objective-c - 如何找到 objective-c 中加载的pdf文件的总页数?

ios - 将手势 UITapGestureRecognizer 添加到 UILabel 后应用程序崩溃

ios - 如何将文本从 SafariViewController 快速获取到我们的应用程序?