Skip to content

Instantly share code, notes, and snippets.

@pejalo
Created April 12, 2018 17:19
Show Gist options
  • Save pejalo/5b8a59fe6d96d4a547f619c1d906428a to your computer and use it in GitHub Desktop.
Save pejalo/5b8a59fe6d96d4a547f619c1d906428a to your computer and use it in GitHub Desktop.
Extension for UIStackView to align arranged subviews to left or right
import UIKit
extension UIStackView {
/// [Source](https://www.iamsim.me/uistackview-left-align-without-stretching/)
public func alignArrangedSubviewsToLeft() {
increaseArrangedSubviewsContentHuggingPriority()
let stretchingView = getStretchingViewWithLowContentHuggingPriority()
addArrangedSubview(stretchingView)
}
/// [Source](https://www.iamsim.me/uistackview-left-align-without-stretching/)
public func alignArrangedSubviewsToRight() {
increaseArrangedSubviewsContentHuggingPriority()
let stretchingView = getStretchingViewWithLowContentHuggingPriority()
insertArrangedSubview(stretchingView, at: 0)
}
private func increaseArrangedSubviewsContentHuggingPriority() {
for view in arrangedSubviews {
view.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
}
}
private func getStretchingViewWithLowContentHuggingPriority() -> UIView {
let stretchingView = UIView()
stretchingView.setContentHuggingPriority(UILayoutPriority(rawValue: 1), for: .horizontal)
stretchingView.backgroundColor = .clear
stretchingView.translatesAutoresizingMaskIntoConstraints = false
return stretchingView
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment