Is there an easy way to get (or simply display) the text from a given line in a UILabel?
My UILabel is correctly displaying my text and laying it out beautifully bu
The accepted answer is very good.
I refactored two places:
changed 10000 to CGFloat.greatestFiniteMagnitude
Added it to an extension
of UILabel
I also want to mention, if you create the label by setting the frame it works fine. If you use autolayout then dont forgot to call
youLabel.layoutIfNeeded()
to get correct frame size.
Here is the code:
extension UILabel {
var stringLines: [String] {
guard let text = text, let font = font else { return [] }
let ctFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
let attStr = NSMutableAttributedString(string: text)
attStr.addAttribute(kCTFontAttributeName as NSAttributedString.Key, value: ctFont, range: NSRange(location: 0, length: attStr.length))
let frameSetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude), transform: .identity)
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
guard let lines = CTFrameGetLines(frame) as? [Any] else { return [] }
return lines.map { line in
let lineRef = line as! CTLine
let lineRange: CFRange = CTLineGetStringRange(lineRef)
let range = NSRange(location: lineRange.location, length: lineRange.length)
return (text as NSString).substring(with: range)
}
}
}