2017-02-21 37 views
0

我创建了一个UIView类:约束在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

你不调用父类。总是首先调用超类(超)初始化器。

延伸阅读: Concepts in Objective-C Programming

例子:

self = [super initWithFrame:frame]; 
+0

你能解释一下吗?像什么,我需要添加到我的代码 –

+0

这不是问题监守@AlmogHamdani你无论如何要做到这一点它工作没有约束 –

+1

罚款。 – shallowThought