UIScrollView AutoLayout

最近改一個BUG,遇到了一個使用AutoLayout讓內容撐開UIScrollView的場景; 試了半天才搞定撐開和能夠滾動,特此記錄一下。swift

代碼以下:bash

//
//  ViewController.swift
//  ScrollViewAutoLayoutDemo
//
//  Created by Crazy凡 on 2019/4/2.
//  Copyright © 2019 kongkaikai. All rights reserved.
//

import UIKit
import SnapKit

class ViewController: UIViewController {
    let scrollView = UIScrollView()
    let testlabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        view.addSubview(scrollView)
        scrollView.addSubview(testlabel)
        scrollView.snp.makeConstraints { (maker) in
            maker.center.equalToSuperview()
            maker.width.lessThanOrEqualTo(UIScreen.main.bounds.width - 60)
            maker.height.lessThanOrEqualTo(UIScreen.main.bounds.height - 80).priority(.required)

            // 保障UIScrollView能夠被撐開,low 是爲了不約束衝突
            maker.height.equalTo(testlabel.snp.height).priority(.low)
        }

        testlabel.numberOfLines = 0
        testlabel.snp.makeConstraints { (maker) in
            maker.top.left.bottom.right.equalToSuperview()
            maker.width.equalToSuperview()

            // 保障能夠正確的計算contentSize
            maker.height.greaterThanOrEqualToSuperview()
        }
        testlabel.text = "測試字符串,多寫一些測試撐開效果"
    }
}

複製代碼
相關文章
相關標籤/搜索