我的自动布局有一个非常奇怪的问题。当我将一个简单的普通视图放入superview并以编程方式附加约束时,它的工作方式与我期望的完全相同。但是,当我对自身具有子视图的自定义视图执行相同操作时,约束无法正常工作。
我设置了自定义视图的自动布局:
- (void) initialiseSubviews
{
self.backgroundColor = [UIColor whiteColor];
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, self.frame.size.width, 20.0)];
headerLabel.backgroundColor = [self tintColor];
[self addSubview:headerLabel];
NSDictionary * viewDict = NSDictionaryOfVariableBindings(headerLabel);
NSArray * horiz = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[headerLabel]-|" options:0 metrics:nil views:viewDict];
NSArray * vert = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[headerLabel]" options:0 metrics:nil views:viewDict];
NSArray * height = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[headerLabel(20)]" options:0 metrics:nil views:viewDict];
[headerLabel addConstraints:height];
[self addConstraints:horiz];
[self addConstraints:vert];
}
+ (BOOL) requiresConstraintBasedLayout
{
return YES;
}
- (BOOL) translatesAutoresizingMaskIntoConstraints
{
return NO;
}
- (CGSize) intrinsicContentSize
{
return CGSizeMake(200.0, 120.0);
}
...并将其添加到内容视图中,如下所示:
- (SSNodeView *) addNodeAtPoint:(CGPoint)point
{
// Prepare the node view
SSNodeView * nodeView = [SSNodeView nodeView];
[self.gridView addSubview:nodeView];
NSDictionary * viewDict = NSDictionaryOfVariableBindings(nodeView);
NSArray * width = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[nodeView(>=300)]" options:0 metrics:0 views:viewDict];
NSArray * height = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[nodeView(>=200)]" options:0 metrics:0 views:viewDict];
[nodeView addConstraints:width];
[nodeView addConstraints:height];
// Set its autolayout properties
NSDictionary * metricDict = @{@"x":[NSNumber numberWithFloat:point.x], @"y":[NSNumber numberWithFloat:point.y]};
NSArray * horizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-x-[nodeView]" options:0 metrics:metricDict views:viewDict];
NSArray * vertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-y-[nodeView]" options:0 metrics:metricDict views:viewDict];
[self.gridView addConstraints:horizontal];
[self.gridView addConstraints:vertical];
// Update and layout constraints
[self.gridView layoutIfNeeded];
return nodeView;
}
...然而,它始终出现在原始帧中,而不是针对自动布局进行调整!如果我切换到一个简单的普通UIView并使用完全相同的布局代码它完美地工作,当我将带有或没有约束的子视图添加到我的主视图时,事情只会出错。感觉就像我应该做的事情,使自定义布局正常工作,但我不知道它可能是什么。
有人有任何想法吗?
-Ash
答案 0 :(得分:0)
好的,似乎已经发生了变化,并且覆盖translatesAutoresizingMaskIntoConstraints
的方法不再按预期工作;删除该方法并设置它引用的属性至少可以解决我遇到的一些问题。