我有UITableViewCell
,有两个标签和一个开关。当切换值更改为状态Off
时,我会删除其中一个标签,当更改为On
时,会将其添加回视图。我用过自动布局。因此,当我想要添加时,我在删除时添加了丢失的约束。这是我的代码片段
- (void)willUpdateCell:(SampleTableViewCell *)cell{
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
if ([cell.messageSwitch isOn]) {
cell.messageDescription = [UILabel new];
cell.messageDescription.translatesAutoresizingMaskIntoConstraints = NO;
cell.messageDescription.text = self.messages[indexPath.row][@"description"];
cell.messageDescription.numberOfLines = 0;
cell.messageDescription.lineBreakMode = NSLineBreakByWordWrapping;
[cell.contentView addSubview:cell.messageDescription];
cell.left = [NSLayoutConstraint constraintWithItem:cell.messageDescription
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:cell.messageSwitch
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:0];
cell.bottom = [NSLayoutConstraint constraintWithItem:cell.messageDescription
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:cell.contentView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:15];
cell.top = [NSLayoutConstraint constraintWithItem:cell.messageDescription
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:cell.messageTitle
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:2];
cell.right = [NSLayoutConstraint constraintWithItem:cell.messageDescription
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:cell.contentView
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:15];
[cell.contentView addConstraints:@[cell.bottom,cell.left,cell.right,cell.top]];
}else{
[cell.messageDescription removeFromSuperview];
}
[cell updateFont];
[cell.contentView updateConstraints];
[UIView animateWithDuration:0.5 animations:^{
[cell.contentView setNeedsLayout];
}];
}
我遇到的问题是当开关状态发生变化时缩小行的高度。删除视图后,间距仍然保留。如果我试图重新加载表,tableview表现得很奇怪。我附上了我的代码here供您参考。请告诉我,当删除子视图时,我可以做些什么来使tableview缩小行高。