I have a few UIStackView
that I add programmatically and I want them to have a other Axis
when the app is in say Regular Width and Any Height
.
It this even possible, like it is in the interface builder?
All I bump into on Google is willTransitionToTraitCollection
, but not what I need.
To make it easier to understand what I need:
for i in numberOfItems {
let stackView = UIStackView()
stackView.append... // add views in this new stack view
// here is where I need help:
stackView.axis = horizontal
stackView.addSomething... stackView.axis = vertical if regular width and any height.
existingStackView.append.... stackView
}
Edit:
I found a other way to do, but I get some strange behaviour on iPhone 6+ when I rotate it around. Git repo: https://github.com/bjaskj/iOSStackViewConstraints
class MyStackView: UIStackView {
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Regular {
axis = UILayoutConstraintAxis.Horizontal
} else {
axis = UILayoutConstraintAxis.Vertical
}
}
}
ViewController:
@IBOutlet weak var mainStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
addElement("Name", description: "Saint Petersburg")
addElement("Native name", description: "Санкт-Петербург")
addElement("Country", description: "Russia")
addElement("Federal district", description: "Northwestern")
addElement("Economic region", description: "Northwestern")
addElement("Established", description: "May 27, 1703")
}
func addElement(title:String, description:String) {
let labelTitle = UILabel()
labelTitle.backgroundColor = UIColor.redColor()
labelTitle.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
labelTitle.text = title
labelTitle.textColor = UIColor.whiteColor()
let labelDescription = UILabel()
labelDescription.backgroundColor = UIColor.blueColor()
labelDescription.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
labelDescription.text = description
labelDescription.textColor = UIColor.whiteColor()
let stackHolder = MyStackView()
stackHolder.axis = .Vertical
stackHolder.distribution = .FillEqually
stackHolder.addArrangedSubview(labelTitle)
stackHolder.addArrangedSubview(labelDescription)
stackHolder.spacing = 8
mainStackView.addArrangedSubview(stackHolder)
}
What happens when I rotate iPhone 6+
is this:
But what I expect and get if I start the app in rotated position: