gpt4 book ai didi

ios - 如何在自定义 UITableViewCell 中获取 UILabel 的字体大小?

转载 作者:行者123 更新时间:2023-11-28 08:11:35 24 4
gpt4 key购买 nike

我的 UITableView 带有自定义类的单元格,例如 HistoryCell

单元格 UI 元素在界面构建器中组成并与类属性链接:

@IBOutlet var contentLabel: UILabel!

因为 contentLabel 是多行的,所以我的任务是为这些单元格正确设置高度。我想使用 String.boundingRect 方法计算高度,但它需要 UIFont

我可以在开发时将字体属性从界面构建器复制到代码中,但如果将来要更改字体,则需要代码来修复

相反,我想从内存单元中获取字体
我创建静态实例并将其用于返回字体:

class HistoryCell: UITableViewCell {
private static let instance = HistoryCell()

static func textFont() -> UIFont {
return instance.contentLabel.font
}
}

但是当我调用HistoryCell.textFont 方法时,contentLabelnil

为什么是 nil?
我可以通过其他方式获取单元格元素字体吗?

最佳答案

我猜您已经使用 IBOutlet 连接了 contentLabel,并且当您创建 HistoryCell 实例时,它不会加载 nib 文件引用。因此,它会为您返回 contentLabel 的 nil 对象

你也可以这样做

open func textFont() -> UIFont {
return self.titlelabel.font
}

并使用使用 dequeue func 接收的 cell 对象调用此函数

let cell = tableView.dequeueReusableCell(withIdentifier: "ParallexCell", for: indexPath) as! HistoryCell
let font = cell.textFont()

关于ios - 如何在自定义 UITableViewCell 中获取 UILabel 的字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43627082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com