-
Notifications
You must be signed in to change notification settings - Fork 1
Getting Started
LuRui edited this page Dec 30, 2018
·
4 revisions
This article walks you through how to use LRCustomSpacingStackView in practice.
- Import LRCustomSpacingStackView
import LRCustomSpacingStackView- Set up your
UIStackViewwhatever you prefer. No magic here.
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 10
stackView.alignment = .leading
stackView.distribution = .equalSpacing
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
stackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = trueThis stack view will arrange its subviews vertically with a fixed spacing of 10 point. Note that its height is not constrained, because it will automatically grow after adding self-sizing subviews later.
- Setup your views just like you did before. No magic here
let view1 = UIView()
view1.backgroundColor = .blue
view1.translatesAutoresizingMaskIntoConstraints = false
view1.widthAnchor.constraint(equalToConstant: 300).isActive = true
view1.heightAnchor.constraint(equalToConstant: 200).isActive = true
let view2 = UIView()
view2.backgroundColor = .red
view2.translatesAutoresizingMaskIntoConstraints = false
view2.widthAnchor.constraint(equalToConstant: 300).isActive = true
view2.heightAnchor.constraint(equalToConstant: 100).isActive = true- Add views to the
stackView. Use lr_addArrangedSubview(_:) instead of addArrangedSubview(_:)
stackView.lr_addArrangedSubview(view1)
stackView.lr_addArrangedSubview(view2)
lr_addArrangedSubview(_:) is provided by this library as a UIStackView extension method. It does exactly what addArrangedSubview(\_:) does, and additionally allows us to add custom spacing in a new way later. For now, it should look exactly the same as using addArrangedSubview(_:):
- Let's add some extra spacing! Say, let view1 be 20 points away from the stackView's top, 30 points away from the stackView's left, and 10 points away from the view2's top
view1.lr_stackSpacing = UIEdgeInsets(top: 20, left: 30, bottom: 10, right: 0)