轉貼:
http://gibuloto.com/blog/uitableviewcell-auto-height/ 
動態調整 UITableViewCell 的高度假設有一個這樣的 custom UITableViewCell:  
因為評論的內容可能有好幾行,高度不一定,所以要做以下的處理:
in CommentCell.m
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
#import "CommentCell.h" 
 @implementation  CommentCell 
 @synthesize  avatarImageView ,  userNameLabel ,  timeLabel ,  commentTextLabel ; 
@synthesize  comment ,  delegate ; 
 -  ( void ) awakeFromNib 
{ 
    [ super  awakeFromNib ]; 
 } 
 #pragma mark - UI 
 -  ( void ) fillInfo 
{ 
    // ... 
 
     // 評論 
     NSString  * content  =  [ comment  objectForKey: @"content" ]; 
     double  labelHeight  =  [ self  getCellHeight ]; 
     self . commentTextLabel . numberOfLines  =  0 ;  // 默認值只有 1 行 
     self . commentTextLabel . text  =  content ; 
     self . commentTextLabel . frame  =  CGRectMake ( self . commentTextLabel . frame . origin . x , 
                                              self . commentTextLabel . frame . origin . y , 
                                              self . commentTextLabel . frame . size . width , 
                                              labelHeight ); 
 } 
 -  ( float ) getCellHeight 
{ 
    NSString  * content  =  [ self . comment  objectForKey: @"content" ]; 
     double  commentTextLabelWidth  =  self . commentTextLabel . frame . size . width ;  // 必須給定一個固定的寬度,才能計算可變的高度 
     CGSize  constraint  =  CGSizeMake ( commentTextLabelWidth ,  CGFLOAT_MAX ); 
     CGSize  size  =  [ content  sizeWithFont: self . commentTextLabel . font 
                       constrainedToSize: constraint 
                           lineBreakMode: UILineBreakModeWordWrap ]; 
 
     double  minCommentTextLabelHeight  =  22.0 ; 
     CGFloat  height  =  MAX ( size . height ,  minCommentTextLabelHeight ); 
 
     return  height ; 
 } 
 @end 
 
 
in CommentViewController.m
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
#pragma mark - UITableView 
 -  ( CGFloat ) tableView: ( UITableView  * ) tableView  heightForRowAtIndexPath: ( NSIndexPath  * ) indexPath 
{ 
    if  ( self . comments . count  >  0 )  { 
         CommentCell  * testCommentCell  =  [[ CommentCell  alloc ]  init ]; 
         testCommentCell . comment  =  [ self . comments  objectAtIndex: indexPath . row ]; 
 
         return  68  +  [ testCommentCell  getCellHeight ]  +  10 ; 
     } 
     else  { 
         return  100 ; 
     } 
 } 
 
 
 
沒有留言:
張貼留言