在隐藏互斥子视图

时间:2016-04-26 23:59:57

标签: ios autolayout storyboard xib nslayoutconstraint

ParentView包含ChildView1和ChildView2。这些子视图具有不同的高度。

ChildView1比ChildView2高。仅显示一个子视图,例如,如果ChildView1可见,则隐藏ChildView2。 ChildView1和ChildView2都使用自​​定义XIB。

两个子视图"驱动" ParentView的高度,即AutoLayout约束被连线,使得ParentView与ChildView1或ChildView2一样高,并且没有更高。

问题是隐藏ChildView1并显示ChildView2没有"收缩" ParentView匹配ChildView2的高度。它保持在较高的子视图ChildView1的高度。

致电sizeToFit()setNeedsLayout()不会改变事情。

如何在隐藏ChildView1时强制ParentView匹配ChildView2的高度?

3 个答案:

答案 0 :(得分:4)

隐藏的视图仍然参与布局。除了隐藏它之外,您还需要停用隐藏视图上的约束。

如果您的部署目标是iOS 9或更高版本,则可以将父级设为UIStackView。堆栈视图在布局期间自动忽略其隐藏的子项。

更新

对于所有限制,您不需要单独的出口。你只需要两个插座系列。您可以将一个插座集合连接到多个对象。演示:

creating outlet collections

集合最终连接到故事板中的多个对象:

view controller connections

然后,您可以使用一个语句激活或停用约束集合:

class ViewController: UIViewController {

    @IBOutlet var pinkConstraints: [NSLayoutConstraint]!
    @IBOutlet var greenConstraints: [NSLayoutConstraint]!

    func showPink() {
        NSLayoutConstraint.deactivateConstraints(greenConstraints)
        NSLayoutConstraint.activateConstraints(pinkConstraints)
    }

    func showGreen() {
        NSLayoutConstraint.deactivateConstraints(pinkConstraints)
        NSLayoutConstraint.activateConstraints(greenConstraints)
    }

}

答案 1 :(得分:1)

您可以将父视图设置为与子视图相同的大小

// Match to childView1
CGSize size = childView1.frame.size;
[parentView setFrame:CGRectMake(0,0,size.width,size.height)];

或相反

// Match to childView2
CGSize size = childView2.frame.size;
[parentView setFrame:CGRectMake(0,0,size.width,size.height)];

答案 2 :(得分:0)

通过在ParentView和ChildView1 / ChildView2之间插入中间视图解决了这个问题。这样,ChildView1驱动其包含视图的高度,而不是ParentView,与ChildView2相同。也许不是最干净,但它的工作。 Rob建议使用UIStackView似乎是理想的,但它只需要iOS 8的支持,这对于应用来说暂时不实用。