iOS开发动态计算cell的高度

来源:互联网 发布:软件系统结构设计 编辑:程序博客网 时间:2024/04/28 23:29

在iOS开发过程中,我们经常会用到UITableView, 谈到UITableView当然少不了UITableViewCell.那么有时候我们就会有疑惑,怎么样才能让cell的高度根据文字的大小多少,以及照片的高度来动态设计呢?

下面我们来看一下,到底怎么做才能让cell的高度动态变化,让界面看起来更美观协调一些呢?

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

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

转载出处:http://www.cocoachina.com/ios/20140920/9698.html

0 0
原创粉丝点击