动态调整UITableViewCell高度的实现方法
2013-11-07 09:09
465 查看
动态调整UITableViewCell高度的实现方法
On 04/02/2011, in iOS Dev, by ultragtx有时我们需要动态调整UITableViewCell的高度,根据内容的不同设置不同的高度,以前看到一种实现方法,写得有点麻烦,具体地址找不到了,这里有个更好的(至少我认为),分享一下部分代码。
2012.03.11更新:一年后回来审视儿时的代码,发现heightForRowAtIndexPath那个实现方法确实不太好,会dequeue掉一个可以reuse的cell导致经常都要新创建cell,会导致效率方面的问题,最好用NSString的sizeWithFont:forWidth:lineBreakMode:这一系列的方法计算label的高度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero]; label.tag = 1; label.lineBreakMode = UILineBreakModeWordWrap; label.highlightedTextColor = [UIColor whiteColor]; label.numberOfLines = 0; label.opaque = NO; // 选中Opaque表示视图后面的任何内容都不应该绘制 label.backgroundColor = [UIColor clearColor]; [cell.contentView addSubview:label]; [label release]; } UILabel *label = (UILabel *)[cell viewWithTag:1]; NSString *text; text = [textArray objectAtIndex:indexPath.row]; CGRect cellFrame = [cell frame]; cellFrame.origin = CGPointMake(0, 0); label.text = text; CGRect rect = CGRectInset(cellFrame, 2, 2); label.frame = rect; [label sizeToFit]; if (label.frame.size.height > 46) { cellFrame.size.height = 50 + label.frame.size.height - 46; } else { cellFrame.size.height = 50; } [cell setFrame:cellFrame]; return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; //UITableViewCell *cell = [self cellForRowAtIndexPath:indexPath]; return cell.frame.size.height; } |
相关文章推荐
- BoundedBlockingQueue
- 变量与对话框的交互:UpdateData(FALSE)&&UpdateDate(TRUE)
- stringbuilder简介
- UESTC 1307 —— 数位DP
- Dispatch Queue挂起
- UINavigationController使用详解
- iOS之UITableView之样板代码
- MIUI 们的发展蓝图:“罪恶”秘密背后的金钱和机遇
- 关于VECTOR和DEQUE
- UIKIT框架
- 【LTE基础知识】GUTI(Globally Unique Temporary UE Identity)分配
- latex-suite 备忘
- 使用WatiN进行UI自动化测试
- [原]BluetoothClass详解
- [原]BluetoothClass详解
- 安卓程序代写 网上程序代写[原]BluetoothClass详解
- 【Android 应用开发】BluetoothClass详解
- 【Android 应用开发】BluetoothClass详解
- BluetoothClass详解
- 《hadoop权威指南》学习笔记-hadoop I/O之SequenceFile