HWScrollViewController.m(如何初始化主滚动视图)
- - (void)loadView
- {
- self.scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
- self.scrollView.delegate = self;
- self.view = self.scrollView;
- }
HWListingDetailViewController.m
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- UILabel *priceLabel = [[UILabel alloc] init];
- UIButton *favouriteButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
- [priceLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
- [favouriteButton setTranslatesAutoresizingMaskIntoConstraints:NO];
- [priceLabel setText:@"$125.00"];
- [favouriteButton setTitle:@"Add to Favourites" forState:UIControlStateNormal];
- [self.view addSubview:priceLabel];
- [self.view addSubview:favouriteButton];
- [self.view addConstraints:@[
- [NSLayoutConstraint constraintWithItem:priceLabel
- attribute:NSLayoutAttributeCenterY
- relatedBy:NSLayoutRelationEqual
- toItem:self.view
- attribute:NSLayoutAttributeCenterY
- multiplier:1
- constant:0],[NSLayoutConstraint constraintWithItem:priceLabel
- attribute:NSLayoutAttributeLeft
- relatedBy:NSLayoutRelationEqual
- toItem:self.view
- attribute:NSLayoutAttributeLeft
- multiplier:1
- constant:5],[NSLayoutConstraint constraintWithItem:favouriteButton
- attribute:NSLayoutAttributeCenterY
- relatedBy:NSLayoutRelationEqual
- toItem:self.view
- attribute:NSLayoutAttributeCenterY
- multiplier:1
- constant:0],[NSLayoutConstraint constraintWithItem:favouriteButton
- attribute:NSLayoutAttributeRight
- relatedBy:NSLayoutRelationEqual
- toItem:self.view
- attribute:NSLayoutAttributeRight
- multiplier:1
- constant:5],
}
您可以看到,绿色价格标签正确对齐,但红色按钮离开屏幕左侧. (我给它5像素的偏移量来显示它的位置.)那么,为什么scrollview的右边实际上是左边的?如何正确对齐屏幕右侧?我哪里做错了?这让我疯狂!
感谢任何帮助!
最终布局图片:
我希望最终的布局是这样的:
如果旋转到景观,我会期待它看起来像这样:
解决方法
然而,当涉及到自动布局时,UIScrollViews以独特的方式表现.最好的描述来自这个technical note.有两个选项可用,包括例子,但是每个的摘要.
混合方式
您只需要向UIScrollView添加一个UIView,然后在UIView中添加和定位所有的子视图.这需要您在UIScrollView上手动设置UIView的框架和contentSize.
这可能是您尝试实现的布局最简单的方法.但是,如果contentSize可以更改,则必须手动计算和更新大小.
纯汽车布局方法
此选项使用您的autolayout约束来确定UIScrollView的contentSize.这需要限制到UIScrollView的所有四个边缘,并且不能依赖于UIScrollView的大小.
这个选项比较困难,因为你需要确保你有足够的约束.在您的情况下,您将遇到问题,因为对UIScrollView的顶部和底部没有约束,并且没有约束可用于确定UIScrollView的宽度.但是,当您必须处理动态内容时,此选项将非常惊人,因为它将根据需要调整contentSize的大小.
就个人而言,我会用纯汽车布局方法去.处理动态内容大小的能力使得额外的约束设置值得.
如果你发布你想要的最终布局,我会更新我的答案,以反映.
更新
根据您发布的图像,这是我使用纯自动布局方法组织子视图的方式.主要区别在于UIScrollView现在是UIViewControllers视图的子视图.
- - UIView (self.view)
- - UIScrollView (scrollView)
- - UIView (contentView)
- - UIImageView,UIButtons,UILabels,etc.
scrollView需要约束,所以它的边缘是0px from self.view.
contentView需要约束,所以它的边缘是从scrollView的0px,它的宽度等于self.view.这样就可以使scrollView的contentSize在旋转设备时更新.
接下来只需按照你想要的方式放置所有的图像和标签.标签将需要被限制在左右,以便它可以计算其高度.需要注意的是,ContentView将根据其子视图的约束来确定其高度,因此您将需要约束“链接”contentView的顶部和底部.一个简单的例子就像这样.
> contentView顶部到imageView顶部> imageView height ==一些值> imageView底部到标签顶部>标签底部到contentView底部