如何在UIStackView中堆叠自定义视图

时间:2017-06-29 11:33:07

标签: ios swift autolayout uistackview

注意:我在使用iOS UI时非常新。

我想创建一个自定义视图,在其中堆叠自定义视图。

所以我创建了自定义UIStackView

class CustomStackView: UIStackView {

    func addItem(color:UIColor){
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "RowView", bundle: bundle)
        let rowView = RowView();
        let view = nib.instantiate(withOwner: rowView, options: nil).first as! UIView
        rowView.addSubview(view)
        rowView.view.backgroundColor = color;
        addArrangedSubview(rowView)
    }

}

class RowView :UIView{

    @IBOutlet var view: UIView!

    override public var intrinsicContentSize: CGSize {
        return CGSize(width: view.frame.width,height:view.frame.height)
    }
}

RowView.xib我创建了一个简单的测试布局:

Simulated Metrics = Freeform
Height = 100

enter image description here

ViewController.swift:

class ViewController: UIViewController {

    @IBOutlet weak var customStackView: CustomStackView!
    @IBOutlet weak var constraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        customStackView.addItem(color: UIColor.red)
        customStackView.addItem(color: UIColor.blue)
        customStackView.addItem(color: UIColor.green)
    }

    @IBAction func click(_ sender: Any) {
        constraint.constant = -customStackView.frame.height
        UIView.animate(withDuration: 4, animations: {
            self.view.layoutIfNeeded();
        },completion:nil)
    }

}

结果:

enter image description here

第一项和第二项正确显示,但第三项高于预期。

此外,如果我点击按钮(应隐藏Stackview),请保留" extra"高度可见:

enter image description here

我该如何解决?

编辑:尝试添加尾随视图的@KristijanDelivuk解决方案。并没有奏效。在视图中添加青色我得到了这个结果:

override func viewDidLoad() {
    super.viewDidLoad()
    customStackView.addItem(color: UIColor.red)
    customStackView.addItem(color: UIColor.blue)
    customStackView.addItem(color: UIColor.green)
    let view = UIView();
    view.heightAnchor.constraint(equalToConstant: 50).isActive = true;
    view.backgroundColor = UIColor.cyan;
    customStackView.addArrangedSubview(view)
}

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以尝试添加一个空的UIView作为UIStackView的最后一个元素:

所以你的层次结构应该是这样的:

- STACKVIEW
-- 1ST ADDED CUSTOM VIEW 
-- 2ND ADDED CUSTOM VIEW
-- 3RD ADDED CUSTOM VIEW
-- EMPTY UIVIEW

空UIView将从第3个视图中获取所有未分配的空间,并且所有空间都应正确显示。

为了在隐藏/显示stackview之后重新定位按钮,您可以创建例如" top constraint"然后点击将顶部约束高度更改为( - )stackview.height或(+)stackview.height - 这不应该是任何问题。