gpt4 book ai didi

ios - 以编程方式布置 UIScrollView,并为其 subview 添加自动布局,但它不滚动

转载 作者:行者123 更新时间:2023-11-28 08:01:26 25 4
gpt4 key购买 nike

我试图弄清楚 UIScrollView 是如何工作的,我向它添加了一些具有不同 backgroundColor 属性的 subview 。我用 ios9 autolayout 布置了 subview ,但即使 View 在屏幕之外,UIScrollView 仍然不会滚动。

import UIKit

class ViewController: UIViewController {

let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.backgroundColor = .gray
return sv
}()

override func viewDidLoad() {
super.viewDidLoad()

view.addSubview(scrollView)

scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

let view1 = UIView()
view1.backgroundColor = .red

let view2 = UIView()
view2.backgroundColor = .blue

let view3 = UIView()
view3.backgroundColor = .green

let view4 = UIView()
view4.backgroundColor = .purple

let views = [view1, view2, view3, view4]

for view in views {
scrollView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
}

view1.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
view1.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
view1.heightAnchor.constraint(equalToConstant: 140).isActive = true
view1.widthAnchor.constraint(equalToConstant: 140).isActive = true

view2.topAnchor.constraint(equalTo: view1.bottomAnchor, constant: 100).isActive = true
view2.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
view2.heightAnchor.constraint(equalToConstant: 140).isActive = true
view2.widthAnchor.constraint(equalToConstant: 140).isActive = true

view3.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 50).isActive = true
view3.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
view3.heightAnchor.constraint(equalToConstant: 140).isActive = true
view3.widthAnchor.constraint(equalToConstant: 140).isActive = true

view4.topAnchor.constraint(equalTo: view3.bottomAnchor, constant: 20).isActive = true
view4.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
view4.heightAnchor.constraint(equalToConstant: 140).isActive = true
view4.widthAnchor.constraint(equalToConstant: 140).isActive = true
}

}

最佳答案

在 UIScrollViews 中使用自动布局时,您必须将 subview 固定到 ScrollView 的顶部和底部,这样 ScrollView 才能计算其 contentSize。

添加这一行修复它:

view4.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true

关于ios - 以编程方式布置 UIScrollView,并为其 subview 添加自动布局,但它不滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46593585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com