標籤:
原文: http://blog.csdn.net/crayondeng/article/details/8899577
最近遇到了一個cell高度變化的問題,在找解決辦法的時候,參考了這篇文章,覺得不錯
在寫sina 微博的顯示微博內容時,用到cell進行顯示,那麼就要考慮到不同微博內容導致的cell高度問題。在微博顯示的內容中包括了文字和圖片,那麼就要計算文字部分的高度和圖片部分的高度。這篇博文就記錄一下如何處理cell高度的動態調整問題吧!
一、傳統的方法
在 tableview的delegate的設定高度的方法中進行設定- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath,當然在這個代理方法中需要計算文字的高度以及圖片的高度,然後返回。
1、文字(string)高度的處理;
由於文字的長度的不確定的,所以就要根據這個動態文字長度來電腦顯示文字的的高度
[cpp] view plaincopy
- #define FONT_SIZE 14.0f
- #define CELL_CONTENT_WIDTH 320.0f
- #define CELL_CONTENT_MARGIN 10.0f
-
- NSString *string = @"要顯示的文字內容";
- CGSize size = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAXFLOAT);
- CGSize textSize = [string sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
以上代碼就是計算文字高度。其中size是裝載文字的容器,其中的height設定為maxfloat;然後用方法
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
Returns the size of the string if it were rendered with the specified constraints.就可以知道string的size了
2、圖片高度的處理;
首先你先要下載到圖片,然後CGSize imageViewSize = CGSizeMake(image.size.width,image.size.height);就可以擷取到圖片的size,就可以對你的imageview的frame進行設定了,那麼也就知道了圖片的高度了。
二、非傳統方法
在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath代理方法中處理cell的frame的高度,在tableview的delegate的設定高度的方法中調用這個方法,那麼就可以得到設定好的cell高度。(注意到二者方法的執行順序:heightForRowAtIndexPath這個代理方法是先執行的,後執行cellForRowAtIndexPath)
[cpp] view plaincopy
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *CellIdentifier = @"Cell";
-
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil) {
- //cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
- //這個方法已經 Deprecated
-
- cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
-
- }
- CGRect cellFrame = [cell frame];
- cellFrame.origin = CGPointMake(0, 0);
-
- //擷取cell的高度的處理
-
- cellFrame.size.height = ***;
- [cell setFrame:cellFrame];
- return cell;
-
- }
稍微解釋一下,注意到cell初始化的時候是CGRectZero,然後[cell frame]擷取cell的frame,讓後就可以對cell的高度進行處理後,setFrame 重新設定cell 的frame了。
接下來就是在heightForRowAtIndexPath這個方法中調用。
[cpp] view plaincopy
- - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
-
- UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
- return cell.frame.size.height;
- }
[轉] iOS TableViewCell 動態調整高度