我尝试使用 UIView 实现以下设计,它应该全部使用自动布局完成并且没有硬编码框架:
我用这样的“for 循环”来完成它:
CGFloat y_coordinate = 0;
for(int i = 0;i < 3;i++)
{
UIView * testView = [UIView new];
testView.frame = CGRectMake(testView.frame.origin.x, y_coordinate, testView.frame.size.width, testView.frame.size.height);
testView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *viewsDictionary = @{@"testView":testView};
testView.backgroundColor = [UIColor redColor];
[self.view addSubview:testView];
//View should have the same Width and Height and a little Padding between them!
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:testView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:0.5
constant:-4]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:testView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:testView
attribute:NSLayoutAttributeHeight
multiplier:1
constant:-4]];
if(i % 2) {
//odd
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[testView]-0-|"
options:0
metrics:nil
views:viewsDictionary]];
//Here i need the Height of the View and not hard coded like here...but how?
y_coordinate += 200;
} else {
//even
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[testView]"
options:0
metrics:nil
views:viewsDictionary]];
}
}
我的问题是我不知道如何使用自动布局将 View 正确地放置在彼此之下?
最佳答案
我给你的建议是在线学习自动布局教程,清楚地了解 View 在“自动布局”下是如何布局的。 一个这样的例子就是 Ray Wenderlich 的教程。虽然本教程并未专门介绍以编程方式进行自动布局,但它确实让您清楚地了解如何借助自动布局功能放置 View 。 http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1
关于ios - 以编程方式使用自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26140957/