I have designed my custom Cell in IB, subclassed it and connected my outlets to my custom class. I have three subviews in cell content which are: UIView (cdView) and two labels (titleLabel and emailLabel). Depending on data available for each row, sometimes I want to have UIView and two labels displayed in my cell and sometimes only two labels. What I am trying to do is to set constraints that way if I set UIView property to hidden or I will remove it from superview the two labels will move to the left. I tried to set UIView leading constraint to Superview (Cell content) for 10px and UILabels leading Constraints for 10 px to the next view (UIView). Later in my code

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(IndexPath *)indexPath {
    
    // ...

    Record *record = [self.records objectAtIndex:indexPath.row];
    
    if ([record.imageURL is equalToString:@""]) {
         cell.cdView.hidden = YES;
    }
}

我把手机藏起来了。cdView和我想要标签移动到左边,但他们在细胞中保持相同的位置。我试着移除细胞。cdView从superview,但它也没有工作。我附上了图片,以澄清我是什么。

我知道如何通过编程来做到这一点,我不是在寻找解决方案。我想要的是在IB中设置约束,我希望如果其他视图被删除或隐藏,我的子视图将动态移动。有可能在IB自动布局中做到这一点吗?

.....

当前回答

正确的方法是禁用isActive = false的约束。但是请注意,取消激活约束会删除并释放它,因此必须为它们提供强出口。

其他回答

在我的例子中,我将高度约束的常数设置为0.0f,并将隐藏属性设置为YES。

为了再次显示视图(带有子视图),我做了相反的事情:我将高度常数设置为非零值,并将隐藏属性设置为NO。

在运行时期间添加或删除约束是会影响性能的重量级操作。然而,有一个更简单的选择。

对于希望隐藏的视图,设置宽度约束。用一个领先的水平间隙约束其他视图到该视图。

要隐藏,请将width约束的.常量更新为0.f。其他视图将自动向左移动以占据位置。

更多细节请看我的另一个答案:

如何在运行时改变标签约束?

这是一个老问题,但我仍然希望它能有所帮助。来自Android,在这个平台上,你有一个方便的方法isVisible隐藏它从视图,但也没有考虑框架时,自动布局绘制视图。

使用extension和“extend”uiview,你可以在ios中做类似的功能(不确定为什么它不在UIKit中)这里是swift 3中的实现:

    func isVisible(_ isVisible: Bool) {
        self.isHidden = !isVisible
        self.translatesAutoresizingMaskIntoConstraints = isVisible
        if isVisible { //if visible we remove the hight constraint 
            if let constraint = (self.constraints.filter{$0.firstAttribute == .height}.first){
                self.removeConstraint(constraint)
            }
        } else { //if not visible we add a constraint to force the view to have a hight set to 0
            let height = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal , toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 0)
            self.addConstraint(height)
        }
        self.layoutIfNeeded()
    }

为了帮助别人,我构建了一个使用可视格式约束的helper类。我在我当前的应用程序中使用它。

AutolayoutHelper

它可能有点适合我的需要,但您可能会发现它很有用,或者您可能想修改它并创建自己的帮助器。

我必须感谢Tim的回答,这个关于UIScrollView和本教程的回答。

我将使用水平堆栈视图。当子视图被隐藏时,它可以移除框架。

在下面的图像中,红色视图是您的内容的实际容器,并有10pt的尾部空间到橙色的父视图(ShowHideView),然后只需将ShowHideView连接到IBOutlet并以编程方式显示/隐藏/删除它。

这是视图可见/安装的时候。

这是当视图被隐藏/未安装时。