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

前端 未结 10 1680
孤街浪徒
孤街浪徒 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:34

    Swift 3 – Xcode 8.1

    I've put together code from the previous answers to create a Swift 3, Xcode 8.1-compatible extension to UILabel returning the first line of the label.

    import CoreText
    
    extension UILabel {
    
       /// Returns the String displayed in the first line of the UILabel or "" if text or font is missing
       var firstLineString: String {
    
        guard let text = self.text else { return "" }
        guard let font = self.font else { return "" }
        let rect = self.frame
    
        let attStr = NSMutableAttributedString(string: text)
        attStr.addAttribute(String(kCTFontAttributeName), value: CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil), range: NSMakeRange(0, attStr.length))
    
        let frameSetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
        let path = CGMutablePath()
        path.addRect(CGRect(x: 0, y: 0, width: rect.size.width + 7, height: 100))
        let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
    
        guard let line = (CTFrameGetLines(frame) as! [CTLine]).first else { return "" }
        let lineString = text[text.startIndex...text.index(text.startIndex, offsetBy: CTLineGetStringRange(line).length-2)]
    
        return lineString
      }
    }
    

    To use it, simple call firstLineString on your UILabel instance like this:

    let firstLine = myLabel.firstLineString
    

提交回复
热议问题