如果UIStackView
对象包含三个或更多项目,则当我从堆栈视图中删除项目然后重新添加它们时,项目之间的间距保持正常。
但是,如果相同的UIStackView
对象包含两个项,当我删除并重新添加它们时,它们之间的间距就会消失。
导致此行为的原因是什么?如何解决?
这是与我的简单视觉相关的简单代码:
import UIKit
class StackViewTest : UIViewController {
let stackView = UIStackView()
let stackViewLabels = [
//When I use three labels instead of two, everything works normally!
//UILabel(),
UILabel(),
UILabel()
]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "reloadStackView"))
//initialize stackView
stackView.spacing = 30
stackView.axis = .Horizontal
stackView.distribution = .EqualSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
stackView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
//initialize stackView labels
var labelIndex = 0
for label in stackViewLabels {
label.text = "Label \(labelIndex++)"
}
//initialize tap count label
tapCountLabel.numberOfLines = 3
tapCountLabel.lineBreakMode = .ByWordWrapping
view.addSubview(tapCountLabel)
updateTapCount()
}
//this function is called each time the screen is tapped
func reloadStackView() {
for view in stackView.arrangedSubviews {
stackView.removeArrangedSubview(view)
view.removeFromSuperview()
}
for label in stackViewLabels {
stackView.addArrangedSubview(label)
}
updateTapCount()
}
//for updating the number of screen taps:
let tapCountLabel = UILabel(frame: CGRectMake(0, 30, 400, 90))
var screenTapCount = 0
func updateTapCount() {
tapCountLabel.text = "Tap Count: \(screenTapCount++)\nstackView.spacing: \(stackView.spacing)\n(tap the screen to reload the stackview)"
}
}