动态自定义UITableViewCell的高度基于Swift中的标签文本长度

Aao*_*oIi 6 ios swift

我一直在尝试使用swift做一个动态单元格,使用swift来支持IOS7,heightForRowAtIndexPath但我只找到了Objective-c代码,是否可以让其他人帮助我将这段代码重写为swift?

 // 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;
Run Code Online (Sandbox Code Playgroud)

正是这句话(如何将其转换为swift):

CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:19] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping]
Run Code Online (Sandbox Code Playgroud)

我尝试将其转换为(但它不能作为原始目标-c):

 var requiredSize: CGSize = originalString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(19.0)])
Run Code Online (Sandbox Code Playgroud)

Ste*_*tic 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
Run Code Online (Sandbox Code Playgroud)