最近改一个BUG,遇到了一个使用AutoLayout让内容撑开UIScrollView的场景; 试了半天才搞定撑开和可以滚动,特此记录一下。
代码如下:
//// ViewController.swift// ScrollViewAutoLayoutDemo//// Created by Crazy凡 on 2019/4/2.// Copyright © 2019 kongkaikai. All rights reserved.//import UIKitimport SnapKitclass 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 = "测试字符串,多写一些测试撑开效果" }}复制代码