我有一个大小为 20x40 的 UIView,它已作为 ViewController 的子视图添加。较小的 UIView 可以在屏幕上拖动,并且根据它被拖动到的位置,UIView 将重置“X”坐标以粘在屏幕边缘。
但是,我想使用/学习“自动布局”向此子视图添加约束,以在横向和纵向模式下保持相同的宽度和高度。
到目前为止的代码:
self.anotherView = [[UIView alloc] initWithFrame: CGRectMake (0.0,(self.view.frame.size.height/2)-45.0f-self.navigationController.navigationBar.frame.size.height,20.0,45.0f)];
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(dragging:)];
[self.anotherView addGestureRecognizer:panRecognizer];
[self.anotherView setBackgroundColor: [UIColor blueColor]];
self.anotherView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview: self.anotherView];
[self.view bringSubviewToFront:self.anotherView];
NSDictionary *views = @{@"subview" : self.anotherView, @"superview" : self.view};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subview(==20)]|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[subview(==40)]" options:NSLayoutFormatAlignAllBaseline metrics:nil views:views]];
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.anotherView attribute:NSLayoutAttributeBaseline relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:self.view.bounds.size.height];
[self.view addConstraint:constraint];
但是,上面的代码给了我以下错误:
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:0x8b4ef80 H:|-(0)-[UIView:0x8b4eab0] (Names: '|':UIView:0x8b4cc80 )>",
"<NSLayoutConstraint:0x8b4f020 H:[UIView:0x8b4eab0(20)]>",
"<NSLayoutConstraint:0x8b4f0f0 H:[UIView:0x8b4eab0]-(0)-| (Names: '|':UIView:0x8b4cc80 )>",
"<NSAutoresizingMaskLayoutConstraint:0x8aa1d30 h=--& v=--& H:[UIView:0x8b4cc80(320)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x8b4f0f0 H:[UIView:0x8b4eab0]-(0)-| (Names: '|':UIView:0x8b4cc80 )>
Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
我在这里到底做错了什么?另外,我正在使用 Storyboard,只有这个视图作为子视图添加到 ViewController。请在下面找到当前 UI 外观的屏幕截图。