iOS開發動態計算cell的高度

來源:互聯網
上載者:User

標籤:

在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 + 4 * 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開頭的都是宏定義的數值。

iOS開發動態計算cell的高度

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.