为啥这些约束不起作用?
Posted
技术标签:
【中文标题】为啥这些约束不起作用?【英文标题】:Why are these constraints not working?为什么这些约束不起作用? 【发布时间】:2013-03-25 18:14:56 【问题描述】:我有一个滚动视图,我想在 viewDidLoad 方法中添加到我的超级视图。我使用以下代码执行此操作:
[self.view addSubview:self.scroll];
NSMutableArray *constraints = [NSMutableArray arrayWithCapacity:4];
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.scroll
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1
constant:0]];
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.scroll
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1
constant:0]];
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.scroll
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0]];
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.scroll
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0]];
[self.view addConstraints:constraints];
滚动视图旨在放置在视图的底部,并且它的高度应该是超级视图高度的一半。
我收到以下错误:
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
( "", "", "", “” )
将尝试通过打破约束来恢复
请有人告诉我我做错了什么吗?谢谢。
【问题讨论】:
你是否在代码中创建了滚动视图? 不,它被放置在 nib 文件中,但在视图之外......所以我可以看到放置在滚动视图中的所有元素......我有一个名为 scroll 的插座(代码中的 self.scroll片段) 您可以尝试添加 [self.scroll setTranslatesAutoresizingMaskIntoConstraints:NO];看看这是否有帮助,但通常你只需要在代码中创建视图时这样做。 这确实有帮助!谢谢!!!! 【参考方案1】:rdelmar 解决了这个问题:
您可以尝试添加 [self.scroll setTranslatesAutoresizingMaskIntoConstraints:NO]
【讨论】:
以上是关于为啥这些约束不起作用?的主要内容,如果未能解决你的问题,请参考以下文章