2015-05-04 72 views
6

我一直在試圖做一個動態單元格標籤使用swift支持IOS7 heightForRowAtIndexPath但我只找到objective-c代碼,是否有可能讓別人來幫忙我把這段代碼改寫成swift?基於Swift中標籤文本長度的動態定製UITableViewCell的高度

// Fetch yourText for this row from your data source.. 
    NSString *yourText = [yourArray objectAtIndex:indexPath.row]; 

    CGSize lableWidth = CGSizeMake(300, CGFLOAT_MAX); // 300 is fixed width of label. You can change this value 
    CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:19] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping]; // You can put your desire font 

    // Here, you will have to use this requiredSize and based on that, adjust height of your cell. I have added 10 on total required height of label and it will have 5 pixels of padding on top and bottom. You can change this too. 
    int calculatedHeight = requiredSize.height+10; 
    return (float)calculatedHeight; 

正是這個聲明(如何將其轉換爲SWIFT):

CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:19] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping] 

我試圖將其轉換爲(但並不作爲原始Objective-C的工作):

var requiredSize: CGSize = originalString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(19.0)]) 
+0

這裏是剛剛進入直通it.http最好的例子://www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift –

+0

按照此鏈接: http://stackoverflow.com/questions/9827126/change-the-uitableviewcell-height-according-to-amount-of-text/42111135#42111135> – mumu

回答

6

也許有可能沒有UILabel這樣做,但這工作得很好。

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 10000)) 
label.text = someText 
label.numberOfLines = 100 
label.font = UIFont(name: "Times New Roman", size: 19.0) 
label.sizeToFit() 
return label.frame.height + 10