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

ao

我一直在尝试使用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;

正是这个语句(如何将其转换为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)])
Stefan Salatic

也许可以不使用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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章