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自动布局中做到这一点吗?

.....

当前回答

这是另一个使用优先级约束的解决方案。其思想是将宽度设置为0。

创建容器视图(橙色)并设置宽度。 创建内容视图(红色),并设置尾随空间10pt为superview(橙色)。注意尾随空间约束,有两个优先级不同的尾随约束。低(=10)和高(<=10)。这对于避免歧义很重要。 设置橙色视图的宽度为0以隐藏视图。

其他回答

使用两个UIStackView水平和垂直,当堆栈中的某些子视图视图被隐藏时,其他堆栈子视图将被移动,使用Distribution ->按比例填充垂直堆栈中的两个uilabel,并需要设置宽度和高度约束的第一个UIView

只需使用UIStackView和一切将工作正常。 不需要担心其他约束,UIStackView将自动处理空间。

我的项目使用了UILabel的自定义@IBDesignable子类(以确保颜色,字体,插图等的一致性),我已经实现了如下内容:

override func intrinsicContentSize() -> CGSize {
    if hidden {
        return CGSizeZero
    } else {
        return super.intrinsicContentSize()
    }
}

这允许label子类参与自动布局,但隐藏时不占用空间。

这是另一个使用优先级约束的解决方案。其思想是将宽度设置为0。

创建容器视图(橙色)并设置宽度。 创建内容视图(红色),并设置尾随空间10pt为superview(橙色)。注意尾随空间约束,有两个优先级不同的尾随约束。低(=10)和高(<=10)。这对于避免歧义很重要。 设置橙色视图的宽度为0以隐藏视图。

最简单的解决方案是使用UIStackView(水平)。添加到堆栈视图:带标签的第一个视图和第二个视图。 然后将first view的isHidden属性设置为false。 所有约束都将自动计算和更新。