How to get text / String from nth line of UILabel?

前端 未结 10 1633
孤街浪徒
孤街浪徒 2020-11-27 05:27

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

10条回答
  •  遥遥无期
    2020-11-27 05:31

    The accepted answer is very good.

    I refactored two places:

    1. changed 10000 to CGFloat.greatestFiniteMagnitude

    2. Added it to an extension of UILabel

    3. 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)
            }
        }
    }
    

提交回复
热议问题