Last active
March 29, 2024 07:26
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome!