iOS開發動態計算cell的高度,ios動態cell高度
在iOS開發過程中,我們經常會用到UITableView,談到UITableView當然少不了UITableViewCell.那麼有時候我們就會有疑惑,怎麼樣才能讓cell的高度根據文字的大小多少,以及照片的高度來動態設計呢?下面我們來看一下,到底怎麼做才能讓cell的高度動態變化,讓介面看起來更美觀協調一些呢?
//動態設定cell的高度+ (CGFloat)heightForRowWithModel:(PhotoInfo *)photoInfo{ //1.圖片的高度 //讓圖片等比例縮放 //(1)擷取圖片 UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ZZ" ofType:@"png"]]; CGFloat imageHeight = [self heightForImage:image]; //2.文本的高度 CGFloat textHeight = [self heightForText:photoInfo.introduction]; //3.返回cell 的總高度 return kPhotoCell_TitleLabel_Height + imageHeight + textHeight + 4 * kPhotoCell_MarginBetween;}//單獨計算圖片的高度+ (CGFloat)heightForImage:(UIImage *)image{ //(2)擷取圖片的大小 CGSize size = image.size; //(3)求出縮放比例 CGFloat scale = kPhotoCell_Width / size.width; CGFloat imageHeight = size.height * scale; return imageHeight;}//單獨計算文本的高度+ (CGFloat)heightForText:(NSString *)text{ //設定計算文本時字型的大小,以什麼標準來計算 NSDictionary *attrbute = @{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize]}; return [text boundingRectWithSize:CGSizeMake(kPhotoCell_Width, 1000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrbute context:nil].size.height;}
代碼中k開頭的都是宏定義的數值
ios 開發怎設定tableviewcell的高度隨著內容的多少變化
在heightForRowAtIndexPath代理方法裡
NSString *inforStr = @“”; UIFont *font = [UIFont systemFontOfSize:15]; CGSize size = CGSizeMake(300,2000); CGSize labelsize = [inforStr sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping]; return labelsize.height;
總結了幾種設定UITableView的cell動態高度的方法
一:改變它的載入順序,或者說白了就是計算好cell高度後,再次讓它載入heightForRowAtIndexPath方法;二:直接在heightForRowAtIndexPath計算,做判斷,直接返回對應的高度。以下是第一種方法的執行個體:UITableView設定單元格的高度的方法- (CGFloat)tableView:(UITableView// Somewhere in your header:NSIndexPath *selectedCellIndexPath;// And in the implementation file:- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {selectedCellIndexPath = indexPath;// Forces the table view to call heightForRowAtIndexPath[tableView reloadRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationNone];}- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {// Note: Some operations like calling [tableView cellForRowAtIndexPath:indexPath]// will call heightForRow and thus create a stack overflowif(selectedCellIndexPath != nil&& [selectedCellIndexPath compare:indexPath] == NSOrderedSame)return 128;return 64;}reloadRowsAtIndexPaths方法將重新調用heightForRowAtIndexPath使單元格改變高度。