let label = UILabel()
label.text = "Label Text"
Get label width before addSubview.
view.addSubview(label)
You can use this function width(forHeight height: CGFloat, font: UIFont)
for calculating string width.
let tetxWidth = "Label Text".width(forHeight: 15, font: .systemFont(ofSize: 14))
extension String {
func width(forHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return ceil(boundingBox.width)
}
}