让cell的高度根据文字的大小多少,以及照片的高度来动态设计

在iOS开发过程中,我们经常会用到UITableView, 谈到UITableView当然少不了UITableViewCell.那么有时候我们就会有疑惑,怎么样才能让cell的高度根据文字的大小多少,以及照片的高度来动态设计呢?下面我们来看一下,到底怎么做才能让cell的高度动态变化,让界面看起来更美观协调一些呢?

 

 

  1. //动态设置cell的高度  
  2.   
  3. + (CGFloat)heightForRowWithModel:(PhotoInfo *)photoInfo  
  4. {  
  5.     //1.图片的高度  
  6.     //让图片等比例缩放  
  7.     //(1)获取图片  
  8.     UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ZZ" ofType:@"png"]];  
  9.     CGFloat imageHeight = [self heightForImage:image];  
  10.     //2.文本的高度  
  11.     CGFloat textHeight = [self heightForText:photoInfo.introduction];  
  12.     //3.返回cell 的总高度  
  13.     return kPhotoCell_TitleLabel_Height + imageHeight + textHeight + 44 * kPhotoCell_MarginBetween;  
  14. }  
  15. //单独计算图片的高度  
  16. + (CGFloat)heightForImage:(UIImage *)image  
  17. {  
  18.     //(2)获取图片的大小  
  19.     CGSize size = image.size;  
  20.     //(3)求出缩放比例  
  21.     CGFloat scale = kPhotoCell_Width / size.width;  
  22.     CGFloat imageHeight = size.height * scale;  
  23.     return imageHeight;  
  24. }  
  25. //单独计算文本的高度  
  26. + (CGFloat)heightForText:(NSString *)text  
  27. {  
  28.     //设置计算文本时字体的大小,以什么标准来计算  
  29.     NSDictionary *attrbute = @{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize]};  
  30.     return [text boundingRectWithSize:CGSizeMake(kPhotoCell_Width, 1000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrbute context:nil].size.height;  
  31. }  


代码中k开头的都是宏定义的数值

posted @ 2014-09-22 22:48  784692237  阅读(724)  评论(0)    收藏  举报