尝试在 ViewController 中使用 tableView 实现以下方法:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return HeightCalculator.height(with: text, inViewController: self)
}
然后添加以下类:
import UIKit
class HeightCalculator {
let title: String
let viewController: UIViewController
class func height(with title: String, inViewController viewController: UIViewController) -> CGFloat {
let calculator = HeightCalculator(title: title, viewController: viewController)
return calculator.height
}
init(title: String, viewController: UIViewController) {
self.title = title
self.viewController = viewController
}
var height: CGFloat {
let contentHeight = title.heightWithConstrainedWidth(width: defaultWidth, font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1))
}
}
你需要在你的字符串上添加以下扩展来获取高度:
import UIKit
extension String {
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
}
使用heightForRowAt 计算高度,计算它的计算器类(contentHeight)和获取高度的扩展名。您可以调整计算器类以传递字体,以便它可以使用此字体将其传递给heightWithConstrainedWidth 方法。