您的位置:首页 > 其它

动态计算tablviewcell高度

2016-06-11 11:40 344 查看
根据实体类的属性,计算出要显示的高度,然后设置tableview代理

- (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";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: