UIView类崩溃应用程序中的约束

时间:2017-02-21 13:58:04

标签: objective-c ios10

我创建了一个UIView类:

UIViewClass.h

#import <UIKit/UIKit.h>

@interface UIViewClass : UIView

@end

UIViewClass.m

#import "UIViewClass.h"

@implementation UIViewClass

- (instancetype)initWithFrame:(CGRect)frame
{

    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [doneBtn addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
    [doneBtn setTitle:@"Done" forState:UIControlStateNormal];
    [doneBtn.titleLabel setFont:[UIFont fontWithName:@"AvenirNext-Bold" size:20]];
    doneBtn.frame = CGRectMake(0, 0, 75, 40);
    doneBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:doneBtn];

    [self addConstraints:[NSLayoutConstraint
                      constraintsWithVisualFormat:@"H:|-180-[doneBtn]"
                      options:0
                      metrics:nil
                      views:NSDictionaryOfVariableBindings(doneBtn)]];

    return self;

}

@end

我将其称为 UIViewClass *viewClass = [[UIViewClass alloc] initWithFrame:CGRectMake(0,0,150,150)];

当我尝试构建它时,它构建时没有错误,但是当我启动应用程序时,应用程序崩溃了。我知道问题是约束,因为没有它,它会顺利运行。有人能告诉我出了什么问题吗?

1 个答案:

答案 0 :(得分:1)

您没有调用超类。始终首先调用超类(超级)初始化程序。

进一步阅读: Concepts in Objective-C Programming

示例:

self = [super initWithFrame:frame];