嵌套堆栈视图:以编程方式附加它时,子堆栈视图不在其父堆栈视图中

时间:2016-06-13 05:02:41

标签: swift autolayout uistackview

我正在尝试实现嵌套堆栈视图,其中一个堆栈视图位于另一个堆栈视图中。我的代码是here。我目前的代码如下所示。

@IBOutlet weak var verticalStackView: UIStackView!
let blueImageView = UIImageView()
blueImageView.backgroundColor = UIColor.blueColor()
blueImageView.image = UIImage(named: "just some image")
blueImageView.snp_makeConstraints { (make) in
  make.height.width.equalTo(34)
}

let greenImageView = UIImageView()
greenImageView.backgroundColor = UIColor.greenColor()
greenImageView.image = UIImage(named: "just some image")
// This is just from SnapKit
greenImageView.snp_makeConstraints { (make) in
  make.height.width.equalTo(34)
}

let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.Horizontal
stackView.distribution = UIStackViewDistribution.EqualSpacing
stackView.alignment = UIStackViewAlignment.Center
stackView.spacing = 16.0
stackView.addArrangedSubview(blueImageView)
stackView.addArrangedSubview(greenImageView)
stackView.translatesAutoresizingMaskIntoConstraints = false;
// This is just from SnapKit
verticalStackView.snp_makeConstraints { (make) in
  make.height.equalTo(70)
}
verticalStackView.addSubview(stackView)

当我尝试运行时,它就是这样。

Just the image

如您所见,子堆栈视图stackView位于层次结构中的父堆栈视图(verticalStackView)之下。但定位是关闭的。

我是Swift,AutoLayout和StackViews的新手。有谁可以帮助指出我在这里缺少的东西?

谢谢!

2 个答案:

答案 0 :(得分:1)

所以我在阅读之后已经找到了解决方案..

@IBOutlet weak var verticalStackView: UIStackView!
let blueImageView = UIImageView()
blueImageView.backgroundColor = UIColor.blueColor()
blueImageView.image = UIImage(named: "buttonFollowCheckGreen")
blueImageView.snp_makeConstraints { (make) in
  make.height.width.equalTo(34)
}

let greenImageView = UIImageView()
greenImageView.backgroundColor = UIColor.greenColor()
greenImageView.image = UIImage(named: "buttonFollowCheckGreen")
greenImageView.snp_makeConstraints { (make) in
  make.height.width.equalTo(34)
}

let firstLineStackView = UIStackView()
firstLineStackView.axis = UILayoutConstraintAxis.Horizontal
firstLineStackView.distribution = UIStackViewDistribution.Fill
firstLineStackView.alignment = UIStackViewAlignment.Center
firstLineStackView.spacing = 8.0

firstLineStackView.addArrangedSubview(blueImageView)
firstLineStackView.addArrangedSubview(greenImageView)
firstLineStackView.translatesAutoresizingMaskIntoConstraints = false;

let redImageView = UIImageView()
redImageView.backgroundColor = UIColor.redColor()
redImageView.image = UIImage(named: "buttonFollowCheckGreen")
redImageView.snp_makeConstraints { (make) in
  make.height.width.equalTo(34)
}

verticalStackView.addArrangedSubview(firstLineStackView)

我只需使用addArrangedSubview代替addSubview,然后让Auto布局完成其余工作。只是为了修复图片视图的位置和大小,我还修改了verticalStackView的alignmentfillleading

答案 1 :(得分:0)

greenImageView.heightAnchor.constraint(equalToConstant:34).isActive = true greenImageView.widthAnchor.constraint(equalToConstant:34).isActive = true

它将被解决