ScrolView的Autolayout约束

  在使用autoLayout的时候,针对一般的view只需要添加四个位置信息便可以确定一个view的位置了;但是因为scrolView本身控件的特殊性,我们设置的约束只是控制了scrollView的Frame。如果scrollView想要滑动,我们还要设置scrollView的ContentSize,在使用代码的时候的时候我们可以通过代码来实现,非常的简单;
- (void)viewDidLoad {
UIView *contentView;

contentView = [[UIView alloc] initWithFrame:CGRectMake(0,0,contentWidth,contentHeight)];

[scrollView addSubview:contentView];

// DON'T change contentView's translatesAutoresizingMaskIntoConstraints,
// which defaults to YES;

// Set the content size of the scroll view to match the size of the content view:
[scrollView setContentSize:CGSizeMake(contentWidth,contentHeight)];

 /* the rest of your code here... */

}

当我们使用Xib的时候我们怎么实现呢?
由于ScrollView的contentSize在Xib上是自动计算的,那么我们就需要在xib上为ScrollView的子视图计算好Size,这样的话编译器就会自动的确定ScrollView的contentSize了,成功实现我们的需求。

通过一个简单的项目,我们可以深刻的理解ScrollView的contentSize在Xib上的计算原理:

创建一个Xib文件,在上面创建一个ScrollView,然后设置ScrollView的基本约束即top,left,bottom,right四个方向定死(或者设置top,left,right,height)像设置普通View的约束一样,注意,这时ScrollView并没有报错,但是当我们向ScrollView上面添加一个lable命名contentLb时,ScrollView便出现红色的报错信息,这是因为ScrollView不知道怎么计算本身的contentSize。

这里写图片描述

因为缺少ContentSize的控制信息。这时我们开始添加控制信息,现在要求contentLb的text变得很多的时候,可以上下滑动scrollView来查看所有的text,如此,我们先控制水平方向的contentSize,如上图所示:(设置left,right,width信息)设置contenLb距离左右的边距,注意这个边距不是ScrollView的边距,而是背景View的edage;
水平方向的视图的ContentSize设置完成后,开始设置计算垂直方向的ContentSize:(设置top,height,bottom)
这里写图片描述

如上图,我们添加contentLb距离ScrollView的top,bottom,和contentLb的height就可以确定scrollView在垂直方向上的contentSize了。
看下效果:
1.设置contentLb的高度和文字

@IBOutlet weak var contentLb: UILabel!
    @IBOutlet weak var contentTH: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()
        let content:String = "你好,hello,world!\n你好,hello,world!\n你好,hello,world!\n你好,hello,world!\n你好,hello,world!\n你好,hello,world!\n你好,hello,world!\n你好,hello,world!\n"
        contentLb.text = content
        contentTH.constant = 200
2.运行,如下图;

这里写图片描述

项目地址:https://github.com/LINDreaming/DailyTools
感兴趣的欢迎留言交流~
参看资料:
https://www.raywenderlich.com/159481/uiscrollview-tutorial-getting-started
https://developer.apple.com/library/content/technotes/tn2154/_index.html

发布了35 篇原创文章 · 获赞 9 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/SunFlowerInRain/article/details/76030505