【发布时间】:2013-08-14 22:29:38
【问题描述】:
出于我正在创建的框架的目的,我需要设置 UIView 对象的框架属性,但是当 AutoLayout 开启时,我不能这样做。 我的想法是我可以从 UIView 对象中删除所有布局约束,然后根据我想要的框架创建新的。
所以这就是我所拥有的,但它给我一个错误(如下)不起作用。
//Remove current constraints
[self.view removeConstraints:self.view.constraints];
//create x constraint based on new x value
NSLayoutConstraint *xConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view.superview
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:self.x];
// add new x constrain
[self.view.superview addConstraint:xConstraint];
//create y constraint based on new y value
NSLayoutConstraint *yConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view.superview
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:self.y];
[self.view.superview addConstraint:yConstraint];
//create width constraint based on new width value
NSLayoutConstraint *widthConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:self.width];
[self.view.superview addConstraint:widthConstraint];
//create height constraint based on new height value
NSLayoutConstraint *heightConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:self.height];
[self.view.superview addConstraint:heightConstraint];
这是在运行时发生的:
编辑
将 [self.view addConstraint:heightConstraint]; 更改为 [self.view.superview addConstraint:heightConstraint]; 元素后显示,但我在控制台中收到以下消息
错误
可能至少以下列表中的一个约束是您不想要的。试试这个:(1)查看每个约束并尝试找出您不期望的; (2) 找到添加了一个或多个不需要的约束的代码并修复它。 (注意:如果您看到不理解的 NSAutoresizingMaskLayoutConstraints,请参阅 UIView 属性 translatesAutoresizingMaskIntoConstraints 的文档)
(
"<NSLayoutConstraint:0x91475c0 H:|-(1)-[UIButton:0x728ab00](LTR) (Names: '|':UIScrollView:0x72845b0 )>",
"<NSLayoutConstraint:0x729dad0 H:|-(25)-[UIImageView:0x7284920](LTR) (Names: '|':UIScrollView:0x72845b0 )>",
"<NSLayoutConstraint:0x72924d0 UIButton:0x728ab00.leading == UIImageView:0x7284920.leading>"
)
【问题讨论】:
-
响应您的编辑:正如您的错误所暗示的,可能存在 NSAutoresizingMaskLayoutConstraints 与您手动创建的约束冲突。您需要将 self.view 的 translatesAutoresizingMaskIntoConstraints 属性设置为 NO 以防止出现此问题。编辑:刚刚看到您的第二次编辑,此评论不正确。
-
旁注:我认为对于 heightConstraint,您应该将第二个属性设置为 NSLayoutAttributeNotAnAttribute。
标签: iphone ios objective-c constraints autolayout