AutoLayout的问题与在NIB文件中定义并在StoryBoard中使用的自定义视图
我已经在NIB文件中定义了一个自定义的视图,并且想在一个StoryBoard中实例化一个副本,但是我遇到了有关自动布局的问题。
在一个简单的例子中,自定义视图具有固定大小的单个标签并且垂直和水平居中,全部使用自动布局。
文件所有者被设置为我的class级,它有一个出口到顶视图。 在自定义视图实现中,我执行:
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if(self) { [[NSBundle mainBundle] loadNibNamed:@"FMCompassView" owner:self options:nil]; [self addSubview:self.topView]; } return self; }
现在,在我的故事板中,我添加了一个UIView,将它的类设置为我的自定义类,然后再使用自动布局将其设置为在页面上的大小和居中。
而我的小工具的位置和大小正确,但它的内容不resize,如下所示:
从NIB加载之后,我尝试添加更多的约束条件,如下所示:
UIView* subV = self.topView; NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(subV); [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[subV]|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:viewsDictionary]]; [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subV]|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:viewsDictionary]];
但是这会导致无效的布局限制。
任何想法如何得到这个工作?
干杯!
从加载NIB创build的视图需要被告知不要将自动resize掩码转换为约束,即使NIB的内容实际上是在启用了自动布局的情况下创build的。
所以在加载NIB之后,在将其顶视图添加到自定义视图之前,我需要调用:
[self.topView setTranslatesAutoresizingMaskIntoConstraints:NO];
除了上面提到的mkrus以外,这是我的initWithCoder:自定义类nib的样子:
- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { NSString *className = NSStringFromClass([self class]); self.view = [[[NSBundle mainBundle] loadNibNamed:className owner:self options:nil] firstObject]; [self.view setTranslatesAutoresizingMaskIntoConstraints:NO]; [self addSubview:self.view]; [self.view mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(self); }]; } return self; }
这里解释了这个initWithCoder方法的原因。 我已经添加了Masonry自动布局约束,以便它可以与界面构build器中定义的约束一起工作。
禁用“使用大小类”为我工作。 我不必做mkrus提到的。