在代码中创建NSLayoutConstraints

时间:2012-11-28 10:19:26

标签: iphone ios nslayoutconstraint

这是我第一次尝试使用约束,所以请原谅基本问题。

我希望能够设置一系列约束,以便subView小于视图宽度的75%或视图的宽度。因此,如果我的subView的宽度大于视图宽度的75%,则将其设置为全宽。我想这样做是为了确保subView在iPhone和iPad上显示良好。

这是否可以使用约束?我已经设置了两个约束,但是如何根据视图的宽度告诉约束系统选择哪一个,因为我不确定只能使用优先级来解决这个问题?

// Ensure it's width is either the less than 3 quarters of the page width or the full page width (including the gutter margins)
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0.75 constant:0];
[self.constraints addObject:constraint];

constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
[self.constraints addObject:constraint];

// Add the constraints to the page
[self addConstraints:self.constraints];

任何帮助都会因为陷入困境而受到高度赞赏。

戴夫

2 个答案:

答案 0 :(得分:1)

您是否有任何理由不能仅根据平台应用适当的约束?

NSLayoutConstraint *constraint;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0.75 constant:0];
}
else {
  constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
}
[self addConstraint:constraint];

另外,根据您的评论,您是否尝试过使用优先级尚不清楚......是否有效?

答案 1 :(得分:0)

正如所讨论的,似乎自动布局无法在MacOS 10.8版本中处理此问题。因此,我建议在标准代码中实现它。

相关问题