NSLayoutConstraint constraintWithVisualFormat无法引用superView

时间:2013-05-05 02:30:05

标签: ios objective-c nslayoutconstraint visual-format-language

以下是一些代码:

UIView *c = [[UIView alloc] initWithFrame:CGRectZero];
[self addSubview:c];
c.translatesAutoresizingMaskIntoConstraints = NO;
c. backgroundColor = [UIColor lightGrayColor];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[c(>=600)]-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(c)]] ;
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[c]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(c)]] ;![enter image description here][1]

为什么它看起来像这样?是什么东西搞砸了我的superView?

Image of messed constraint]

以下是我的包含视图的设置方式: IB setup of containing view

2 个答案:

答案 0 :(得分:0)

c的超级视图是self。不是self.superview

所以这些行应该是:

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

此外,UIView的指定初始化程序为-initWithFrame:,只是调用init并不能保证正常工作。所以第一行应该是

UIView *c = [[UIView alloc] initWithFrame:CGRectZero];

答案 1 :(得分:0)

确定。它现在看起来像约束失败是因为持有一切的视图是UIScrollView的子类。