【发布时间】:2016-08-23 02:09:08
【问题描述】:
我正在尝试在容器视图 (C1) 中添加 3 个自定义视图(redView、greenView、yellowView),这样所有自定义视图(redView、greenView、yellowView)都在以编程方式使用自动布局约束彼此下方。我希望容器视图(C1)的大小与其子视图的大小相同,所以输出应该是这样的。
红色、绿色和黄色视图只是为了显示预期的结果。其实我的自定义视图是这样的。
我正在使用自动布局来执行此操作。这是我执行此操作的代码。 RatingsSingleView 是我的自定义视图,如上图所示。
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *ratingsContainerView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView *previousTopView = self.ratingsContainerView;
for(int i = 0; i < 3; ++i) {
RatingsSingleView *view = [[RatingsSingleView alloc] init];
view.translatesAutoresizingMaskIntoConstraints = NO;
[self.ratingsContainerView addSubview:view];
NSLayoutConstraint *topConstraint = nil;
if(i == 0) {
// Making the first subview top aligned to the container View top
topConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:previousTopView attribute:NSLayoutAttributeTop multiplier:1.0 constant:10.0];
} else{
// Making the second and third subview top aligned to the view above it
topConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:previousTopView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:10.0];
}
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.ratingsContainerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.0];
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.ratingsContainerView attribute:NSLayoutAttributeRight multiplier:1.0 constant:10.0];
[self.ratingsContainerView addConstraint:topConstraint];
[self.ratingsContainerView addConstraint:leftConstraint];
[self.ratingsContainerView addConstraint:rightConstraint];
if(i == 2) {
// Adding last subview bottom to the container View bottom
NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.ratingsContainerView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10.0];
[self.ratingsContainerView addConstraint:bottomConstraint];
}
previousTopView = view;
}
}
@end
所以问题是我没有得到预期的结果。我将容器视图固定在左右边缘,并在情节提要中将其高度设置为 0。一旦我运行上面的代码,我会得到以下结果。
有人可以指导我在这里做错了什么。谢谢
【问题讨论】:
-
那么问题是什么?
-
这可以通过 VFL 更简单地完成
-
我对VFL不是很熟悉,你能给我举个例子吗。
标签: ios layout uiview autolayout nslayoutconstraint