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

.....

当前回答

以下是我如何重新对齐我的uiviews来得到你的解决方案:

拖拽一个UIImageView放到左边。 拖拽一个UIView并把它放到UIImageView的右边。 在UIView中拖放两个uilabel,它的前导约束和尾随约束为零。 将包含2个标签的UIView的前置约束设置为superview而不是UIImagView。 如果UIImageView被隐藏,设置前置约束常量为10像素到superview。ELSE,设置前置约束常量为10px + UIImageView。宽度+ 10像素。

我自己制定了一个拇指规则。当你必须隐藏/显示任何约束可能受到影响的uiview时,在uiview中添加所有受影响/依赖的子视图,并以编程方式更新其前/后/上/下约束常量。

其他回答

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

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

我认为这是最简单的答案。请验证它是否有效:

        StackFullView.layer.isHidden = true
        Task_TopSpaceSections.constant = 0.   //your constraint of top view

点击这里查看https://www.youtube.com/watch?v=EBulMWMoFuw

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

当set hidden = YES时,将uiview和标签之间的约束连接为IBOutlet,并将优先级成员设置为较小的值

我最终创建了2个xib。一个有左视图,一个没有。我在控制器中注册了这两个,然后决定在cellForRowAtIndexPath期间使用哪个。

它们使用相同的UITableViewCell类。缺点是在xib之间有一些重复的内容,但是这些单元格非常基本。好处是我不需要一堆代码来手动管理删除视图、更新约束等。

一般来说,这可能是一个更好的解决方案,因为它们在技术上是不同的布局,因此应该有不同的xib。

[self.table registerNib:[UINib nibWithNibName:@"TrackCell" bundle:nil] forCellReuseIdentifier:@"TrackCell"];
[self.table registerNib:[UINib nibWithNibName:@"TrackCellNoImage" bundle:nil] forCellReuseIdentifier:@"TrackCellNoImage"];

TrackCell *cell = [tableView dequeueReusableCellWithIdentifier:(appDelegate.showImages ? @"TrackCell" : @"TrackCellNoImage") forIndexPath:indexPath];