我有一个UIScrollView
,我想垂直滚动。我正在以编程方式创建UIScrollView
并面临自动布局的问题。
我已将单个子项添加到UIScrollView
中,其余控件已添加到该子视图中。
以下代码会创建滚动视图的UIScrollView
和contentView
lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.keyboardDismissMode = .onDrag
// scrollView.backgroundColor = .red
return scrollView
}()
let contentView: UIView = {
let contentV = UIView()
contentV.translatesAutoresizingMaskIntoConstraints = false
contentV.backgroundColor = UIColor.yellow
return contentV
}()
以下代码会在UIScrollView
内的view
和contentView
内添加UIScrollView
view.addSubview(scrollView)
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8).isActive = true
//内容视图
scrollView.addSubview(contentView)
contentView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
执行此操作后,我尝试在contentView
上添加其他控件但我的view
未正确显示,请参阅以下内容image我已搜索了许多教程,以编程方式添加滚动视图但是无法这样做。