【发布时间】:2012-11-19 13:07:08
【问题描述】:
当使用“动态原型”在情节提要上指定UITableView 内容时,可以将“行高”属性设置为自定义。
在实例化单元格时,不会考虑此自定义行高。这是有道理的,因为我使用哪个原型单元是由我的应用程序代码在单元被实例化时决定的。在计算布局时实例化所有单元格会带来性能损失,所以我理解为什么不能这样做。
然后的问题是,我能否以某种方式检索给定单元重用标识符的高度,例如
[myTableView heightForCellWithReuseIdentifier:@"MyCellPrototype"];
或类似的东西?还是我必须在我的应用程序代码中复制显式行高,随之而来的维护负担?
在@TimothyMoose 的帮助下解决了:
高度存储在单元格本身中,这意味着获取高度的唯一方法是实例化原型。这样做的一种方法是在正常单元回调方法之外预先使单元出列。这是我的小型 POC,它可以工作:
#import "ViewController.h"
@interface ViewController () {
NSDictionary* heights;
}
@end
@implementation ViewController
- (NSString*) _reusableIdentifierForIndexPath:(NSIndexPath *)indexPath
{
return [NSString stringWithFormat:@"C%d", indexPath.row];
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(!heights) {
NSMutableDictionary* hts = [NSMutableDictionary dictionary];
for(NSString* reusableIdentifier in [NSArray arrayWithObjects:@"C0", @"C1", @"C2", nil]) {
CGFloat height = [[tableView dequeueReusableCellWithIdentifier:reusableIdentifier] bounds].size.height;
hts[reusableIdentifier] = [NSNumber numberWithFloat:height];
}
heights = [hts copy];
}
NSString* prototype = [self _reusableIdentifierForIndexPath:indexPath];
return [heights[prototype] floatValue];
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString* prototype = [self _reusableIdentifierForIndexPath:indexPath];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:prototype];
return cell;
}
@end
【问题讨论】:
-
我使用这种方法已经有一段时间了,然后在一个新的故事板上,我得到的单元格的高度(和宽度)尺寸大多为零。即使是非零值也是意想不到的值。禁用尺寸类恢复了此功能。然而,令人失望的是,因为这个“修复”禁用了故事板中的重要功能。但是,这满足了我的迫切需要。
-
我为solving this problem with size classes enabled找到了更完整的解决方案。
标签: ios uitableview uistoryboard