iOS获取UILabel每行文字

public extension UILabel {
    
    public func getLinesArrayOfStringWidth(_ width: CGFloat) -> [String]? {
        
        guard let str = text, str.isEmpty == false, let font = font else {
            return nil
        }
        
        var linesArr = [String]()
        
        let myFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
        
        let attStr = NSMutableAttributedString(string: str)
        
        let paragraphStyle = NSMutableParagraphStyle()
        
        paragraphStyle.lineBreakMode = .byCharWrapping
        
        attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, str.count))
        attStr.addAttribute( NSAttributedString.Key(kCTFontAttributeName as String), value: myFont, range: NSMakeRange(0, str.count))
        
        let frameSetter = CTFramesetterCreateWithAttributedString(attStr)
        
        let path = CGMutablePath()
        
        path.addRect(CGRect(x: 0, y: 0, width: width, height: 10000))
        
        let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
        
        if let lines = CTFrameGetLines(frame) as? [CTLine] {
            lines.forEach { (line: CTLine) in
                let lineRange = CTLineGetStringRange(line)
                
                let lineStr = (str as NSString).substring(with: NSMakeRange(lineRange.location, lineRange.length))
                
                CFAttributedStringSetAttribute(attStr, lineRange, kCTKernAttributeName, NSNumber(value: 0) as CFTypeRef)
                CFAttributedStringSetAttribute(attStr, lineRange, kCTKernAttributeName, NSNumber(value: 0) as CFTypeRef)
                
                linesArr.append(lineStr)
            }
        }
        
        return linesArr
    }
    
}

你可能感兴趣的:(iOS获取UILabel每行文字)