【问题标题】:How to write a Custom UILabel Class using autolayouts如何使用自动布局编写自定义 UILabel 类
【发布时间】:2016-01-04 08:54:14
【问题描述】:

嗨,我对 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

【问题讨论】:

标签: ios objective-c uilabel ios-autolayout


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-05-25
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多