gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:08 24 4
gpt4 key购买 nike

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

最佳答案

也许没有 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

关于ios - 动态自定义 UITableViewCell 的高度基于 Swift 中的标签文本长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30031059/

24 4 0