ios - 如何在滚动视图中添加所有(标签、按钮、子视图)?
问题描述
我在主视图上设计了自动布局,但我忘记添加滚动视图。
我需要以编程方式添加滚动视图或重新设计我的视图吗?
这是我的代码
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)
解决方案
很难说你的视图控制器中有什么样的视图层次结构以及它们有什么样的关系,但这可能会以某种形式或形式帮助你。
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
}
}
推荐阅读
- reactjs - 在本机反应中启用调试器时,没有组件工作(TextInput)
- c# - 如何将整数数组类型的结果从数据库存储到 C# 中的数组?
- vue.js - 如何在 laravel-mix 中使用 vuetify a-la-carte?
- algorithm - 家庭的最小子集,其总和与家庭总和相同
- flutter - 颤振器PixelRatio
- spring - Spring MongoDB:投影数组字段大小(如果存在)
- c# - iText7 & C# 从存储在 MSSQL DB 中的 PDF 中提取页面
- zurb-foundation - 为什么不遵守电子邮件输入的错误消息?
- javascript - NestJS:ValidationPipe 不适用于路由@Param
- python - 动态创建对象又名将字符串转换为python中的类名调用