2015-05-04 70 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