【发布时间】:2015-08-17 21:36:03
【问题描述】:
我目前正在从事一个项目,我在 UITableViewCell 中嵌入了一个 UITableView。
我需要做的是禁用UITableView 的滚动并使UITableView 适合所有行的大小。但由于UITableView 继承自UIScrollView,使用Autolayout 不会强制UITableView 使单元格的高度取决于其contentSize(不是框架)返回UITableViewAutomaticDimension时。
iOS 7 解决方案
这在 iOS 7 之前很容易实现,因为我使用下面的代码获得了 heightForRowAtIndexPath: 下单元格的引用:
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
int height = cell.tableView.contentSize.height;
return height;
但在 iOS 8 中,它给出了 BAD_ACCESS,因为 iOS 8 在调用 cellForRowAtIndexPath: 之前调用了 heightForRowAtIndexPath:。
iOS 8 方法
声明一个属性来保持单元格的引用:
@property (strong, nonatomic) UITableViewCell *prototypeCell
使用方法保存当前单元格对属性的引用以便使用它:
- (id)prototypeCellatIndexPath:(NSIndexPath *)indexPath {
NSString *cellID = @"MyCell";
if (!_prototypeCell) {
_prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:cellID];
}
return _prototypeCell;
}
从原型和它的 contentSize 中获取 UITableViewCell 中的 UITableView 我得到高度,然后通过以下方法将其返回到 heighForRowAtIndexPath: 下:
-(int)heightForThreadAtIndexPath:(NSIndexPath *)indexPath {
_prototypeCell = [self prototypeCellatIndexPath:indexPath];
[_prototypeCell.contentView setNeedsLayout];
[_prototypeCell.contentView layoutIfNeeded];
int footer = [_prototypeCell.tableView numberOfSections]*_prototypeCell.tableView.sectionFooterHeight;
int header = [_prototypeCell.tableView numberOfSections]*_prototypeCell.tableView.sectionHeaderHeight;
int height = ceilf(_prototypeCell.tableView.contentSize.height) + _prototypeCell.tableView.contentOffset.y + _prototypeCell.tableView.contentInset.bottom + _prototypeCell.tableView.contentInset.top + header + footer;
NSLog(@"%i, %i", (int)ceilf(_prototypeCell.tableView.contentSize.height), height);
return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self heightForThreadAtIndexPath:indexPath];
}
问题
我从prototypeCell返回的contentSize.height是错误的,它与UITableView的真实contentSize不匹配,但是当我记录真实的contentSize 在 CustomCell 类 下它显示正确的 contentSize,这与prototypeCell 下的不同。
这让我想知道也许我应该尝试使单元格在特定状态下出列以获得正确的 contentSize,但日志显示相同的值。
我一直在研究并尝试不同的想法,但到目前为止都没有奏效。我不知道是否有人试图实现与我类似的事情,并解决了这个问题。如果您能给我一个想法或其他东西,那就太好了。
【问题讨论】:
-
您是否尝试过调用
[self tableView:tableView cellForRowAtIndexPath:indexPath]数据源方法而不是[self prototypeCellatIndexPath:indexPath];? -
它提供 EXC_BAD_ACCESS
标签: ios uitableview ios8