Skip to content

Instantly share code, notes, and snippets.

@fuxingloh
Last active March 29, 2024 07:26
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save fuxingloh/1768907d25156af30313da48921b0af2 to your computer and use it in GitHub Desktop.
Save fuxingloh/1768907d25156af30313da48921b0af2 to your computer and use it in GitHub Desktop.
iOS Swift: How to find text width, text height or size of UILabel.
extension UILabel {
func textWidth() -> CGFloat {
return UILabel.textWidth(label: self)
}
class func textWidth(label: UILabel) -> CGFloat {
return textWidth(label: label, text: label.text!)
}
class func textWidth(label: UILabel, text: String) -> CGFloat {
return textWidth(font: label.font, text: text)
}
class func textWidth(font: UIFont, text: String) -> CGFloat {
return textSize(font: font, text: text).width
}
class func textHeight(withWidth width: CGFloat, font: UIFont, text: String) -> CGFloat {
return textSize(font: font, text: text, width: width).height
}
class func textSize(font: UIFont, text: String, extra: CGSize) -> CGSize {
var size = textSize(font: font, text: text)
size.width = size.width + extra.width
size.height = size.height + extra.height
return size
}
class func textSize(font: UIFont, text: String, width: CGFloat = .greatestFiniteMagnitude, height: CGFloat = .greatestFiniteMagnitude) -> CGSize {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: height))
label.numberOfLines = 0
label.font = font
label.text = text
label.sizeToFit()
return label.frame.size
}
class func countLines(font: UIFont, text: String, width: CGFloat, height: CGFloat = .greatestFiniteMagnitude) -> Int {
// Call self.layoutIfNeeded() if your view uses auto layout
let myText = text as NSString
let rect = CGSize(width: width, height: height)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
return Int(ceil(CGFloat(labelSize.height) / font.lineHeight))
}
func countLines(width: CGFloat = .greatestFiniteMagnitude, height: CGFloat = .greatestFiniteMagnitude) -> Int {
// Call self.layoutIfNeeded() if your view uses auto layout
let myText = (self.text ?? "") as NSString
let rect = CGSize(width: width, height: height)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: self.font], context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
}
@HuvosFromDarnassus
Copy link

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment