Skip to content

Commit c70f9c2

Browse files
committed
Auto layout now deals with margins around the stackView
1 parent ac1f2a2 commit c70f9c2

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

Example/ScrollableStackView/VerticalLayoutViewController.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ class VerticalLayoutViewController: UIViewController {
2121
scrollable.stackView.distribution = .fillProportionally
2222
scrollable.stackView.alignment = .center
2323
scrollable.stackView.axis = .vertical
24+
scrollable.scrollView.layoutMargins = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
2425
view.addSubview(scrollable)
2526

2627
for _ in 1 ..< 23 {

ScrollableStackView/Classes/ScrollableStackView.swift

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import UIKit
2727
// ScrollView
2828
scrollView = UIScrollView(frame: self.frame)
2929
scrollView.translatesAutoresizingMaskIntoConstraints = false
30+
scrollView.layoutMargins = .zero
3031
self.addSubview(scrollView)
3132

3233
// StackView
@@ -120,9 +121,12 @@ import UIKit
120121
addConstraint(NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
121122
addConstraint(NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0))
122123

123-
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[stackView(==scrollView)]", options: .alignAllCenterX, metrics: nil, views: ["stackView": stackView, "scrollView": scrollView]))
124-
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: .alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
125-
124+
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[stackView]-|", options: [], metrics: nil, views: ["stackView": stackView]))
125+
126+
let margins = scrollView.layoutMarginsGuide
127+
stackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
128+
stackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
129+
126130
didSetupConstraints = true
127131
}
128132
}

0 commit comments

Comments
 (0)