3

我使用iOS9 XCode7 我需要改變細胞的高度動態根據LabelText的高度的iOS:動態高度的UITableViewCell

我用:

self.tableView.rowHeight=UITableViewAutomaticDimension; 

但它不是爲定製細胞工作。在iOS9中刪除 sizetoFit

請提出好的建議。 感謝

+0

您使用的自動佈局? – Joshua

+1

您還需要提供估計的行高參數。只要給self.tableView.estimatedRowHeight = 100。 –

回答

8

給你的標籤約束相對於細胞,頂部,底部,左,右。

比你的單元尺寸將與內容高度成長。

也使您的標籤多(在屬性檢查線路屬性設置爲0)

#pragma mark- Menu table Delegates 

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    return UITableViewAutomaticDimension; 
} 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    return UITableViewAutomaticDimension; 
} 
1

我不太清楚這句話意味着什麼(截圖就已經幫助):

「我需要改變細胞的高度動態根據LabelText的高度」

所以,你有一個UITableViewCell,包含UILabel,並希望每一個細胞在你的表有具體取決於電池的標籤上的高度?

這是我使用的代碼。

在我UITableViewCell類,我將定義一個靜態函數來衡量,並返回高度,是我的.xib文件:

@implementation MikesTableViewCell 

... 

+(CGSize)preferredSize 
{ 
    static NSValue *sizeBox = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     // Assumption: The XIB file name matches this UIView subclass name. 
     NSString* nibName = NSStringFromClass(self); 
     UINib *nib = [UINib nibWithNibName:nibName bundle:nil]; 

     // Assumption: The XIB file only contains a single root UIView. 
     UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject]; 

     sizeBox = [NSValue valueWithCGSize:rootView.frame.size]; 
    }); 
    return [sizeBox CGSizeValue]; 
} 

@end 

然後,在我的UIViewController類,我會告訴我的UITableView到使用這個單元格,找出它的高度。

@property (nonatomic) float rowHeight; 

UINib *cellNib = [UINib nibWithNibName:@"MikesTableViewCell" bundle:nil]; 
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"CustomerCell"]; 

rowHeight = [MikesTableViewCell preferredSize].height; 

... 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return (float)rowHeight; 
} 

同樣,這可能不是你正在尋找的,但我希望這有助於。

1

嘗試。 它很簡單。

一套這樣的高度在heightForRowAtIndexPath方法

float vendorNameHeight = [vendorNameLbl.text heigthWithWidth:width andFont:[UIFont fontWithName:@"Signika-Light" size:21.0]]; 

然後

UILabel*vendorNameLbl=[[UILabel alloc]initWithFrame:CGRectMake(13, 11, 100, 22)]; 
    vendorNameLbl.numberOfLines = 0; 
    [vendorNameLbl sizeToFitVertically];