Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Split string given width of UILabel

How do I split a string given the width of UILabel.

str = "Here is a sample of a long string that wraps at the end of the screen three times." 

width = UIScreen.Main.Bounds.Width

Expected Result

strArray = ["Here is a sample of a long", "string that wraps at the  end", "of the screen three times."]

Look at image:

enter image description here

The Goal is to extract the lines into strings, not wrapping.


1 Answers

try below function

func getStringArrayFromLabel(in label: UILabel) -> [String] {

    /// An empty string's array
    var arrLines = [String]()

    guard let text = label.text, let font = label.font else {return arrLines}

    let rect = label.frame

    let myFont: CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
    let attStr = NSMutableAttributedString(string: text)
    attStr.addAttribute(kCTFontAttributeName as NSAttributedString.Key, value: myFont, range: NSRange(location: 0, length: attStr.length))

    let frameSetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
    let path: CGMutablePath = CGMutablePath()
    path.addRect(CGRect(x: 0, y: 0, width: rect.size.width, height: 100000), transform: .identity)

    let frame: CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
    guard let lines = CTFrameGetLines(frame) as? [Any] else {return arrLines}

    for line in lines {
        let lineRef = line as! CTLine
        let lineRange: CFRange = CTLineGetStringRange(lineRef)
        let range = NSRange(location: lineRange.location, length: lineRange.length)
        let lineString: String = (text as NSString).substring(with: range)
        arrLines.append(lineString)
    }
    return arrLines
}
like image 71
Samir Shaikh Avatar answered Oct 25 '25 06:10

Samir Shaikh