最近改一個BUG,遇到了一個使用AutoLayout讓內容撐開UIScrollView的場景; 試了半天才搞定撐開和可以滾動,特此記錄一下。
程式碼如下:
//
// 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 = "測試字串,多寫一些測試撐開效果"
}
}
複製程式碼