我正在尝试使用 apple dev 中提到的“混合方法”来编写示例代码 link:
我试图在 UIScrollView 中垂直堆叠 3 个 View 。在下面的示例中,UIScrollView 在加载时显示红色 View ,但没有按预期滚动。我可以稍微滚动一下以查看红色 View 下方的绿色 View - 但 ScrollView 弹回并且不会滚动到绿色 View 或其下方的 View (蓝色 View )。我知道我需要一个约束,我试图在 View 1 和 2 之间添加一个约束,以便 view2.top = view1.bottom ,但似乎我遗漏了一些东西。
我还注意到 ScrollView 的内容大小为零(在 viewDidAppear 方法中)。
任何有关我遗漏的提示或有关如何使这种混合方法起作用的帮助都将非常有用!!
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIScrollView* scrollView = ((UIScrollView*)self.view);
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
CGFloat w = self.view.frame.size.width;
CGFloat h = self.view.frame.size.height;
contentView = [[UIView alloc] initWithFrame:CGRectMake(0,0, w, h*3)];
[scrollView addSubview:contentView];
v1 =[[UIView alloc] initWithFrame:CGRectMake(0,0, w, h)];
v2 =[[UIView alloc] initWithFrame:CGRectMake(0,h, w, h)];
v3 =[[UIView alloc] initWithFrame:CGRectMake(0,h*2, w, h)];
v1.backgroundColor = [UIColor redColor];
v2.backgroundColor = [UIColor greenColor];
v3.backgroundColor = [UIColor blueColor];
[contentView addSubview:v1];
[contentView addSubview:v2];
[contentView addSubview:v3];
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:v1
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:v2
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0];
[contentView addConstraint:myConstraint];
scrollView.contentSize = contentView.bounds.size;
}
最佳答案
如果您只是想在 ScrollView 中堆叠 View ,我不明白为什么需要约束。我试过你的代码,它没有像你说的那样很好地滚动,但我认为这是因为你使用 UIScrollView 作为 View Controller 的主视图,你有没有特定的原因想要这样做?
我更改了代码,改为将 UIScrollView 添加到普通 UIView,它按预期完美运行,无需使用任何复杂的约束。请记住使用 UIScrollView *scrollView;
- (void)viewDidLoad {
[super viewDidLoad];
scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:scrollView];
CGFloat w = self.view.frame.size.width;
CGFloat h = self.view.frame.size.height;
contentView = [[UIView alloc] initWithFrame:CGRectMake(0,0, w, h*3)];
[scrollView addSubview:contentView];
v1 =[[UIView alloc] initWithFrame:CGRectMake(0,0, w, h)];
v2 =[[UIView alloc] initWithFrame:CGRectMake(0,h, w, h)];
v3 =[[UIView alloc] initWithFrame:CGRectMake(0,h*2, w, h)];
v1.backgroundColor = [UIColor redColor];
v2.backgroundColor = [UIColor greenColor];
v3.backgroundColor = [UIColor blueColor];
[contentView addSubview:v1];
[contentView addSubview:v2];
[contentView addSubview:v3];
scrollView.contentSize = contentView.bounds.size;
}
关于ios - 具有自动布局混合方法的 UIScrollView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19993595/