2016-07-06 51 views
0

我试图创建动态UITableView,其中cell可以在用户选择cell时展开/折叠。从UITableViewCell隐藏UILabel不会调整contentView

- (void)setUpCell:(DynamicTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { 
    cell.label.text = [self.dataSource objectAtIndex:indexPath.row]; 
    cell.secondLabel.text = [self.dataSource objectAtIndex:self.dataSource.count - indexPath.row - 1]; 
    if ([self.isVisible[indexPath.row] isEqual:@NO]) { 
     cell.secondLabel.hidden = YES; 
    } else { 
     cell.secondLabel.hidden = NO; 
    } 
} 


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return self.dataSource.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    DynamicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    [self setUpCell:cell atIndexPath:indexPath]; 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    DynamicTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    if ([self.isVisible[indexPath.row] isEqual: @YES]) { 
     self.isVisible[indexPath.row] = @NO; 
     cell.secondLabel.hidden = YES; 
    } else { 
     self.isVisible[indexPath.row] = @YES; 
     cell.secondLabel.hidden = NO; 
    } 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static DynamicTableViewCell *cell = nil; 
    static dispatch_once_t onceToken; 

    dispatch_once(&onceToken, ^{ 
     cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    }); 

    [self setUpCell:cell atIndexPath:indexPath]; 

    return [self calculateHeightForConfiguredSizingCell:cell]; 
} 

- (CGFloat)calculateHeightForConfiguredSizingCell:(DynamicTableViewCell *)sizingCell { 
    [sizingCell layoutIfNeeded]; 

    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
    return size.height; 
} 

我分叉this项目,并有测试代码here

单元格大小一旦选定单元格后不变,只隐藏/显示单元格的内容。我试过用UITableViewAutomaticDimension替换显式大小计算。也尝试重新加载单元格。似乎一旦计算出单元尺寸后,它就不会改变。

任何建议,以什么尝试将不胜感激!

回答

1

在iOS开发视图从不崩溃如果您将hidden属性设置为true

相反,您应该使用自动布局。假设您的视图有两个垂直堆叠的标签,将第一个标签贴到contentView的顶部,给它一个高度限制,将第二个标签的顶部固定到第一个标签底部,将第二个标签底部固定到单元格的contentView底部。设置第二个标签的高度,并将此约束保存到一个变量中,我们称它为secondLabelHeightConstraint,现在您可以通过将secondLabelHeightConstraint的值设置为0或您想要的值来折叠和展开单元格。

+0

谢谢!这最终工作,并进行了一些额外的更改以确保UILabel的可变高度。 –

+0

好菲利普,很高兴帮助!我想也许你有一些Android体验?因为在Android中你可以设置view.setVisibility(View.GONE);然后那个观点会“崩溃”。这在iOS中有点棘手。 Autolayout是要走的路:) – Sajjon