我正在尝试在我的视图中使用UIScrollView,因为我要显示的内容不适合屏幕。我纯粹以编程方式工作,似乎无法理解为什么我的UIScrollView在添加约束时根本不起作用。它与框架完美配合,但我认为这是一种笨拙,陈旧的做事方式。我希望能够向滚动视图添加视图,当然,当它离开屏幕时向下滚动。我试图添加一个 topView 作为我希望能够添加的视图之一,并使用scrollview滚动但没有快乐。我哪里错了?任何帮助将受到高度赞赏。
class ScrollTest: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupviews()
}
let topView: UIView = {
let view = UIView()
view.backgroundColor = .yellow
return view
}()
let containerView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view
}()
let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.backgroundColor = .white
sv.translatesAutoresizingMaskIntoConstraints = false
return sv
}()
func setupviews() {
view.addSubview(scrollView)
scrollView.addSubview(containerView)
containerView.addSubview(topView)
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
//
_ = containerView.anchor(scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: scrollView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 700)
_ = topView.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 100, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
}
}
答案 0 :(得分:3)
一些事情。首先,您的containerView
遗失translatesAutoresizingMaskIntoConstraints = false
。其次,UI对象需要四个约束才能生效。所以你缺少一些容器视图。
这是一个完整的工作代码
let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.backgroundColor = .red
sv.translatesAutoresizingMaskIntoConstraints = false
return sv
}()
let containerView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
scrollView.contentSize = CGSize(width: 320, height: 1500)
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
scrollView.addSubview(containerView)
containerView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
containerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
containerView.widthAnchor.constraint(equalToConstant: 200).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
结果就像