Swift中基于标签文本长度的动态自定义UITableViewCell的高度
Posted
技术标签:
【中文标题】Swift中基于标签文本长度的动态自定义UITableViewCell的高度【英文标题】:Dynamic custom UITableViewCell's height based on label text length in Swift 【发布时间】:2015-05-04 13:10:54 【问题描述】:我一直在尝试使用 swift 制作一个带有标签的动态单元格,以支持 heightForRowAtIndexPath
中的 ios7,但我只找到了 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)])
【问题讨论】:
这是最好的例子。raywenderlich.com/87975/… 点击此链接:***.com/questions/9827126/…> 【参考方案1】:也许没有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
【讨论】:
以上是关于Swift中基于标签文本长度的动态自定义UITableViewCell的高度的主要内容,如果未能解决你的问题,请参考以下文章