【发布时间】:2017-02-17 06:41:35
【问题描述】:
所以,我浏览了 Stackoverflow 对这个特定问题的几乎所有答案,甚至浏览了据称教你如何使用滚动视图但它似乎不适用于我的项目的教程。..
这是我目前所知道的,为了让滚动视图正常工作,您首先需要给它一个内容大小。这决定了可滚动的高度等。
我提供了一些代码,让大家更好地了解我如何将所述项目添加到我的滚动视图中。如果我做错了什么,或者如果有更好的方法来做这件事,请告诉我,我对 Swift 和 iOS 开发还很陌生,在我看来,我觉得我做得对。
我正在采取的步骤
- 创建我想要显示的项目(输入字段、图像视图等)
- 将所述项目添加到视图控制器的视图中。 (view.addsubview(etc..))
- 创建一个滚动视图并将其约束设置为与屏幕/视图相同
- 将包含所有项目的视图添加到所述滚动视图中
- 放松,一切都应该完美无瑕?????
这是我的代码,我知道它可能很长,但我认为可能需要它以便理解我的问题的范围
class JobRegistrationController: UIViewController {
// ... Omitted for clarity
lazy var scrollView: UIScrollView = {
let view = UIScrollView(frame: UIScreen.main.bounds)
view.backgroundColor = .red
view.contentSize = CGSize(width: self.view.bounds.width, height: self.view.bounds.height * 2)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
//... Omitted for clarity
let scrollContentView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
// Need so that view controller is not behind nav controller
self.edgesForExtendedLayout = []
view.addSubview(scrollView)
scrollView.addSubview(scrollContentView)
scrollContentView.addSubview(jobTypeField)
scrollContentView.addSubview(jobTypeDividerLine)
// x, y, width and height constraints
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
scrollView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
// x, y, width and height constraints
scrollContentView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollContentView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollContentView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
scrollContentView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
// x, y, width and height constraints
jobTypeField.leftAnchor.constraint(equalTo: scrollContentView.leftAnchor, constant: 20).isActive = true
jobTypeField.topAnchor.constraint(equalTo: scrollContentView.topAnchor).isActive = true
jobTypeField.rightAnchor.constraint(equalTo: scrollContentView.rightAnchor, constant: -8).isActive = true
jobTypeField.heightAnchor.constraint(equalToConstant: 30).isActive = true
// x, y, width and height constraints
jobTypeDividerLine.leftAnchor.constraint(equalTo: scrollContentView.leftAnchor, constant: 20).isActive = true
jobTypeDividerLine.topAnchor.constraint(equalTo: jobTypeField.bottomAnchor).isActive = true
jobTypeDividerLine.rightAnchor.constraint(equalTo: scrollContentView.rightAnchor).isActive = true
jobTypeDividerLine.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
【问题讨论】:
标签: ios swift uiscrollview