我创建了一个简单的项目来以编程方式使用约束来移动一些组件,在这种情况下它只是一个UIPickerView,但不幸的是我总是得到错误代码,我真的不明白它的含义是什么。
这是我的界面:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIPickerView *pickerView;
@end
这是我的实施:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLayoutConstraint *constraint = [NSLayoutConstraint
constraintWithItem:_pickerView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:216.f];
[self.view addConstraint:constraint];
}
这是我在调试器控制台上看到的内容:
2013-09-19 10:44:19.582 Constrain2[3092:c07] Unable to simultaneously satisfy 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)
(
"<NSLayoutConstraint:0x71808f0 V:[UIPickerView:0x7180fd0(216)]>",
"<NSLayoutConstraint:0x71805d0 V:|-(216)-[UIPickerView:0x7180fd0] (Names: '|':UIView:0x7181290 )>",
"<NSAutoresizingMaskLayoutConstraint:0x7184d50 h=--& v=--& V:[UIView:0x7181290(416)]>",
"<NSLayoutConstraint:0x7181740 UIPickerView:0x7180fd0.bottom == UIView:0x7181290.bottom>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x71808f0 V:[UIPickerView:0x7180fd0(216)]>
为什么我有这样的错误信息?我也试过这个教程http://ioscreator.com/auto-layout-in-ios-6-adding-constraints-through-code/,我发现UIButton没问题。但是,它没有使用故事板来创建按钮。而在我的情况下,我通过故事板放置UIPickerView。是什么原因导致了这个问题?
谢谢。答案 0 :(得分:1)
约束0x71808f0想要将选择器的高度设置为216点。
约束0x71805d0想要将选取器的上边缘设置为低于self.view
上边缘216个点。 (这是您在viewDidLoad
中添加的约束。)
约束0x7181740想要将选择器视图的下边缘设置为self.view
的下边缘。
自动布局只能通过将self.view
的高度设置为216 + 216 = 432点来满足这三个约束。
不幸的是,约束0x7184d50想要将self.view
的高度设置为416点。因此,自动布局不能同时满足所有约束条件。
我猜self.view
被限制为416点高,因为你在3.5英寸的屏幕(iPhone 4S或更早版本)上,其高度为480点,并且你打开了状态栏(20分)以及导航栏或工具栏(44分),为视图留下480 - 20 - 44 = 416分。
为什么要在viewDidLoad
中添加约束?