Ant*_*ony 0 objective-c uitableview
在使用动态值时我遇到了一些性能问题heightForRowAtIndexPath:
(我知道这是这种方法,因为如果我设置静态值,响应性会大大增加).我的桌子包含大约3000个细胞.
我明白为什么性能使用动态值(主要是因为该方法的计算必须为表中的每个单元可显示的数据之前进行一次)的时候受苦,但我无法弄清楚如何使它更有效.
在许多的我已经遇到了类似的问题,所提出的解决方案是使用NSString的sizeWithFont方法heightForRowAtIndexPath:,以加快速度.我目前这样做,但表仍然需要约1.5秒加载(并重新加载,这是经常做的).这太长了,我需要优化它.
我正在使用的代码(至少它的本质)如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell;
UILabel *label = nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
label = [[UILabel alloc] initWithFrame:CGRectZero];
// set up label..
[[cell contentView] addSubview:label];
}
NSDictionary *dict = alphabetDict; //dictionary of alphabet letters (A-Z). each key contains an NSArray as its object
CGFloat rightMargin = 50.f; //padding for the tableview's index titles
NSString *key = [[[dict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section];
NSArray *array = [dict objectForKey:key];
NSString *cellText = [array objectAtIndex:indexPath.row];
//TABLE_WIDTH is 268.f, CELL_MARGIN is 14.f
CGSize constraintSize = CGSizeMake(TABLE_WIDTH - (CELL_MARGIN * 2) - rightMargin, 20000.0f);
CGSize labelSize = [cellText sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake(CELL_MARGIN, CELL_MARGIN, TABLE_WIDTH - (CELL_MARGIN * 2) - rightMargin, labelSize.height)];
[label setText:cellText];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//TODO make this faster
NSDictionary *dict = alphabetDict;
CGFloat rightMargin = 50.f;
NSString *key = [[[dict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section];
NSArray *array = [dict objectForKey:key];
NSString *cellText = [array objectAtIndex:indexPath.row];
CGSize constraintSize = CGSizeMake(TABLE_WIDTH - (CELL_MARGIN * 2) - rightMargin, 20000.0f);
CGSize labelSize = [cellText sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + (CELL_MARGIN * 2) + 16.f;
}
Run Code Online (Sandbox Code Playgroud)
有人能指出我正确的方向来进一步简化这些代码吗?谢谢!
我之前遇到过类似的情况.我的解决方案是在执行[tableView reloadData]之前进行所有计算并将高度存储在名为heightsArray的NSMutableArray中.然后
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
[heightsArray objectAtIndex:indexpath.row];
}
Run Code Online (Sandbox Code Playgroud)
向上和向下滚动时无需计算.从数组中读取简单内容.由于计算是在前期完成的,因此最初的阻止将更多,但在滚动时的性能提升方面是值得的.您还可以在后台线程上执行计算,从而节省处理时间.只需在方法中执行所有操作即可在后台线程上调用并准备高度数组.
| 归档时间: |
|
| 查看次数: |
4272 次 |
| 最近记录: |