[英]Get size of UILabel after setting text programmatically
將一些字符串值設置為UILabel的text屬性時
var a : UILabel
a.text = "Variable length string"
autolayout使用約束字體大小,標簽行數等來調整大小。
問題是,如果我需要獲得該標簽的大小以便我(例如)可以決定包含此標簽的表格單元應該有多高,我應該在什么時候成功完成此操作?
試圖在不使用UITableviewAutomaticDimension的情況下解決這個問題。
編輯 :作為可能重復發布的答案有一些相似之處。 然而,我的主要困惑在於我能夠成功且確定地提取UILabel的高度。
已經多次嘗試獲取視圖的大小,但我得到的值不准確,需要采用某種形式使用viewDidLayoutSubviews() 。 我想我不明白布局中發生的事情順序。 對於viewDidLoad()和awakeFromNib()似乎也有所不同,但我可能會對此有所誤解。
如果有人能指出我理解這個方向的正確方向,我將不勝感激
嘗試使用tableView在ViewController中實現以下方法:
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))
}
}
您需要在String上使用以下擴展名來獲取高度:
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
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.