我有几个UIStackView
,我以编程方式添加,我希望他们有一个其他Axis
当应用程序在说Regular Width and Any Height
。如何通过代码在方向更改上添加对UIStackView.Axis的更改?
这甚至可能,就像它在界面生成器?
我所碰到的谷歌是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
}
}
}
的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)
}
您是否尝试更换轴?顺便说一句。一切可能的事情都可以在代码中完成。除了watchOS开发。 – dasdom
更改轴的工作是,但我正在寻找的是当我创建这些'UIStackViews',他们有这添加到它,而不是我必须依靠视图控制器事件来获得通知,然后循环通过我堆栈适应。 – Bjarte