Created
April 12, 2018 17:19
-
-
Save pejalo/5b8a59fe6d96d4a547f619c1d906428a to your computer and use it in GitHub Desktop.
Extension for UIStackView to align arranged subviews to left or right
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
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