Created
January 16, 2020 08:44
-
-
Save alirp88/0191e7ecc81e0ad41b8601710e3ecd10 to your computer and use it in GitHub Desktop.
ScrollView with StackView and auto layout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
override func loadView() { | |
super.loadView() | |
let view = UIView() | |
view.backgroundColor = .systemBackground | |
let scrollView = UIScrollView() | |
scrollView.translatesAutoresizingMaskIntoConstraints = false | |
let stackView = UIStackView(arrangedSubviews: []) | |
for i in 1...100 { | |
let label = UILabel() | |
label.textColor = .label | |
label.text = "\(i)" | |
stackView.addArrangedSubview(label) | |
} | |
stackView.axis = .horizontal | |
stackView.distribution = .equalSpacing | |
stackView.spacing = 8.0 | |
stackView.translatesAutoresizingMaskIntoConstraints = false | |
scrollView.addSubview(stackView) | |
view.addSubview(scrollView) | |
NSLayoutConstraint.activate([ | |
.init(item: view, attribute: .trailing, relatedBy: .equal, toItem: scrollView, attribute: .trailing, multiplier: 1.0, constant: 0.0), | |
.init(item: view, attribute: .centerY, relatedBy: .equal, toItem: scrollView, attribute: .centerY, multiplier: 1.0, constant: 0.0), | |
.init(item: view, attribute: .leading, relatedBy: .equal, toItem: scrollView, attribute: .leading, multiplier: 1.0, constant: 0.0), | |
.init(item: view, attribute: .centerX, relatedBy: .equal, toItem: scrollView, attribute: .centerX, multiplier: 1.0, constant: 0.0), | |
.init(item: scrollView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100.0), | |
.init(item: scrollView, attribute: .trailing, relatedBy: .equal, toItem: stackView, attribute: .trailing, multiplier: 1.0, constant: 0.0), | |
.init(item: scrollView, attribute: .leading, relatedBy: .equal, toItem: stackView, attribute: .leading, multiplier: 1.0, constant: 0.0), | |
.init(item: scrollView, attribute: .top, relatedBy: .equal, toItem: stackView, attribute: .top, multiplier: 1.0, constant: 0.0), | |
.init(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: stackView, attribute: .bottom, multiplier: 1.0, constant: 0.0), | |
.init(item: scrollView, attribute: .height, relatedBy: .equal, toItem: stackView, attribute: .height, multiplier: 1.0, constant: 0.0), | |
]) | |
self.view = view | |
} | |
init() { | |
super.init(nibName: nil, bundle: nil) | |
} | |
required init?(coder: NSCoder) { | |
fatalError() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment