0
let label = UILabel()
label.text = "Label Text"

Get label width before addSubview.

view.addSubview(label)

blancoq
  • 177
  • 1
  • 6

1 Answers1

3

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)
    }
}
emrcftci
  • 3,355
  • 3
  • 21
  • 35
Hayk Brsoyan
  • 186
  • 5