gpt4 book ai didi

ios - 如何在 ScrollView 中添加所有(标签,按钮, subview )?

转载 作者:行者123 更新时间:2023-11-30 11:16:47 25 4
gpt4 key购买 nike

我在主视图上设计了自动布局,但我忘记添加scrollView。

我需要以编程方式添加 ScrollView 或重新设计我的 View 吗?

这是我的代码

var scrollView: UIScrollView!

//viewDid load
let screensize: CGRect = UIScreen.main.bounds
let screenWidth = screensize.width
let screenHeight = screensize.height
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))

for view in view.subviews{

let constraint =

scrollView.addSubview(view)
}
scrollView.contentSize = CGSize(width: screenWidth, height: screenHeight)

最佳答案

很难说你的 View Controller 中有什么样的 View 层次结构以及它们之间有什么样的关系,但这可能会以某种形式或形式对你有所帮助。

class ViewController: UIViewController {
lazy var scrollView: UIScrollView = {
let s = UIScrollView()
s.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(s)
s.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
s.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
s.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
s.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
return s
}()

override func viewDidLoad() {
super.viewDidLoad()

let subviews = view.subviews

// remove all subviews from main view
view.subviews.forEach {
$0.removeFromSuperview()
}

// create vertical stackview, this will help to write less constraints on each subview
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .fill
stackView.axis = .vertical
stackView.distribution = .fill

// all all subviews in stackview
subviews.forEach {
stackView.addArrangedSubview($0)
}

// add stackview in main view
scrollView.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
}
}

这是我在 Storyboard上的 View Controller 。 View Controller 出现在屏幕上后,这两个 View 将被包装在 ScrollView 中。 enter image description here

关于ios - 如何在 ScrollView 中添加所有(标签,按钮, subview )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51667505/

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