Try implementing the following method in your ViewController using tableView:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return HeightCalculator.height(with: text, inViewController: self)
}
Then add the following class:
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.