【发布时间】:2015-02-27 04:58:19
【问题描述】:
使用 Autolayout 时,我无法让 UIScrollView 垂直滚动,我尝试了很多建议。我已经阅读了 Apple 的 technical note,但即使这样似乎也不适用于我的纯自动布局方法。
这是我在容器视图中添加两个 UIView 块 1 和 2 的简单代码。正如许多在线参考所建议的那样,容器视图本身是 UIScrollView 的唯一子项。我将块 1 和块 2 的高度分别设置为 800 点,但滚动视图不会滚动。
- (void)viewDidLoad {
[super viewDidLoad];
// Test UIScrollView with Autolayout, scrolling should word
UIView *mainView = self.view;
UIScrollView* scrollView = [UIScrollView new];
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
scrollView.backgroundColor = [UIColor redColor];
[self.view addSubview:scrollView];
UIView* contentView = [UIView new];
contentView.translatesAutoresizingMaskIntoConstraints = NO;
contentView.backgroundColor = [UIColor greenColor];
[scrollView addSubview:contentView];
UIView* block1 = [[UIView alloc] init];
block1.translatesAutoresizingMaskIntoConstraints = NO;
[block1 setBackgroundColor:[UIColor blackColor]];
[contentView addSubview:block1];
UIView* block2 = [[UIView alloc] init];
block2.translatesAutoresizingMaskIntoConstraints = NO;
[block2 setBackgroundColor:[UIColor blackColor]];
[contentView addSubview:block2];
NSDictionary* viewDict = NSDictionaryOfVariableBindings(mainView,scrollView, contentView, block1, block2);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics:0 views:viewDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics:0 views:viewDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentView(==mainView)]|" options:0 metrics:0 views:viewDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView(==mainView)]|" options:0 metrics:0 views:viewDict]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[block1(==300)]" options:0 metrics:0 views:viewDict]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[block1(==800)]" options:0 metrics:0 views:viewDict]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[block2(==300)]" options:0 metrics:0 views:viewDict]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-810-[block2(==800)]" options:0 metrics:0 views:viewDict]];
}
【问题讨论】:
-
首先,我将块 y 轴上的约束定义为
V:|[block1(==800)]-10-[block2(==block1)]|。至于滚动,我相信您需要在某处定义某物的框架。滚动视图的框架/边界是 (0,0,0,0),即使您在滚动视图中添加内容视图和内容视图中的块,这些边界仍然可以是 (0,0, 0,0) 并且仍然满足您列出的约束...它只是将块添加到大小为 (0,0) 的 UIView 之上。我会 nslog 您的内容视图和滚动视图的边界以确认 -
我认为 UIScrollView 是使用自动布局的最差控件。正如技术说明中所解释的,关键的困难是要求滚动视图中包含的内容不依赖于滚动视图的大小。换句话说,它不像一个普通的容器视图,里面的东西可以随着它们的容器扩展或收缩(因此,设备大小)。他们给出的示例使用了具有固有大小的图像视图。我不认为这对现实生活中的应用很有帮助。
标签: ios objective-c iphone uiscrollview autolayout