In iOS app development, there are times when it’s necessary to determine the number of lines displayed by a UILabel. This helps in making adjustments to the app’s user interface based on the number of lines the UILabel occupies. In this tutorial, we’ll provide a code snippet that calculates the number of lines in a UILabel.
Code snippet to calculating number of lines for UILabel
Swift
x
11
11
1
extension UILabel {
2
func countLines() -> Int {
3
guard let myText = self.text as NSString? else {
4
return 0
5
}
6
// Call self.layoutIfNeeded() if your view uses auto layout
7
let rect = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
8
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: self.font as Any], context: nil)
9
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
10
}
11
}
How to use UILabel extension to find number of lines for UILabel
Swift
xxxxxxxxxx
1
9
1
class ViewController: UIViewController {
2
@IBOutlet weak var labelTitle: UILabel!
3
4
override func viewDidLoad() {
5
if labelTitle.countLines() >= 2 {
6
// Do some stuff
7
}
8
}
9
}