动态计算tablviewcell高度
2016-06-11 11:40
344 查看
根据实体类的属性,计算出要显示的高度,然后设置tableview代理
THEntryCell.m :
注,cellForRowAtIndexPath方法里最好不要太多的代码,把能抽取的代码都抽出来,比如设置属性以及显示在cell子类设置,看起来就清晰简洁的多了
THEntryCell.m:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { THDiaryEntry *entry = [self.fetchedResultsController objectAtIndexPath:indexPath]; return [THEntryCell heightForEntry:entry]; }
THEntryCell.m :
+ (CGFloat)heightForEntry:(THDiaryEntry *)entry { const CGFloat topMargin = 35.0f; const CGFloat bottomMargin = 80.0f; const CGFloat minHeight = 106.0f; UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]]; CGRect boundingBox = [entry.body boundingRectWithSize:CGSizeMake(202, CGFLOAT_MAX) options:(NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName: font} context:nil]; return MAX(minHeight, CGRectGetHeight(boundingBox) + topMargin + bottomMargin); }
注,cellForRowAtIndexPath方法里最好不要太多的代码,把能抽取的代码都抽出来,比如设置属性以及显示在cell子类设置,看起来就清晰简洁的多了
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; THEntryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; THDiaryEntry *entry = [self.fetchedResultsController objectAtIndexPath:indexPath]; [cell configureCellForEntry:entry]; return cell; }
THEntryCell.m:
- (void)configureCellForEntry:(THDiaryEntry *)entry { self.bodyLabel.text = entry.body; self.locationLabel.text = entry.location; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"EEEE, MMMM d yyyy"]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:entry.date]; self.dateLabel.text = [dateFormatter stringFromDate:date]; if (entry.imageData) { self.mainImageView.image = [UIImage imageWithData:entry.imageData]; } else { self.mainImageView.image = [UIImage imageNamed:@"icn_noimage"]; } if (entry.mood == THDiaryEntryMoodGood) { self.moodImageView.image = [UIImage imageNamed:@"icn_happy"]; } else if (entry.mood == THDiaryEntryMoodAverage) { self.moodImageView.image = [UIImage imageNamed:@"icn_average"]; } else if (entry.mood == THDiaryEntryMoodBad) { self.moodImageView.image = [UIImage imageNamed:@"icn_bad"]; } self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame) / 2.0f; if (entry.location.length > 0) { self.locationLabel.text = entry.location; } else { self.locationLabel.text = @"No location"; } }
相关文章推荐
- java创建邮件模板
- UI Components的理解
- 挂载分区
- 3.Android群英传读书笔记-控件架构与自定义控件
- Android中数据文件解析(Json解析)
- 剑指offer(五十七)之二叉树的下一个结点
- C#操作 word代码
- 阅读笔记06
- 第16周阅读程序1(2)
- nodemcu的gpio相关操作
- Mybatis <set>标签
- Mysql 技术内幕(一)
- 如何在命令行模式下查看Python帮助文档---dir、help、__doc__
- Java基础知识强化105:打印数组的方法总结
- h5缓存之数据库
- DIV+CSS clear both清除产生浮动
- js note 1
- cts调试环境的搭建
- 深入理解虚函数表
- uva11134