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

.....

当前回答

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

其他回答

对于谷歌人来说:基于Max的回答,为了解决许多人已经注意到的填充问题,我只是增加了标签的高度,并使用这个高度作为分隔符而不是实际的填充。这个想法可以扩展到任何包含视图的场景。

这里有一个简单的例子:

在本例中,我将Author标签的高度映射到适当的IBOutlet:

@property (retain, nonatomic) IBOutlet NSLayoutConstraint* authorLabelHeight;

当我将约束的高度设置为0.0f时,我们保留了“填充”,因为播放按钮的高度允许它。

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

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

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

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

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

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