如何使用自动布局编写自定义UILabel类



嗨,我是ios的新手。我正在创建一个项目,在这个项目中,我必须处理各种屏幕上的许多标签,所以我必须创建一个从UILabel继承的独立类。我已经设置了该类中的所有标签属性。

但当我运行应用程序时。它显示异常,如:

'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:] 

我的代码:-

自定义标签:-

#import "CustomLabel.h"
@implementation CustomLabel
+(id)getLabel {
    CustomLabel *menu;
    menu = [[self alloc] init];
    [menu setBackgroundColor:[UIColor redColor]];
    [menu setTextColor:[UIColor blackColor]];
     menu.text = @"hjh";
    [menu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@200);
        make.height.equalTo(@30);
        make.left.equalTo(@10);
        make.right.equalTo(@-10);
    }];
    return menu;
}

MainViewController:-

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

@interface MainViewController ()
{
    CustomLabel * mainLabel;
}
@end
@implementation MainViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    mainLabel = [CustomLabel getLabel];
    [self.view addSubview:mainLabel];
}
@end

mas_makeConstraints调用应在将标签添加到视图后进行。从+(id)getLabel中删除此调用,并在创建标签时添加。

CustomLabel* mainLabel = [CustomLabel getLabel];
[self.view addSubview:mainLabel];
[mainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(@200);
    make.height.equalTo(@30);
    make.left.equalTo(@10);
    make.right.equalTo(@-10);
}];

最新更新