我有一些UIStackView
我以编程方式添加的,我希望它们Axis
在应用程序处于 say 时有另一个Regular Width and Any Height
。
这甚至可能,就像在界面构建器中一样?
我在 Google 上遇到的只是willTransitionToTraitCollection
,但不是我需要的。
为了更容易理解我需要什么:
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
}
编辑:
我找到了另一种方法,但是当我旋转 iPhone 6+ 时,我会遇到一些奇怪的行为。Git 仓库: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
}
}
}
视图控制器:
@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)
}