Get specific lines text from multiple line string with CoreText.

CoreText has many powerful function.
and here is the code to slice string by line use CoreText.

// String or AttributedString you want to calculate.
let attStr = NSMutableAttributedString(string: text)
attStr.addAttributes([NSAttributedStringKey.font : font], range: NSMakeRange(0, attStr.length))

let frameSetter = CTFramesetterCreateWithAttributedString(attStr)
// The fit size you want to calculate with given attributedString.
let fitSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let path = CGPath(rect: fitSize, transform: nil)
// Frame from attributedString with given size.
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)

// Slice frame by lines.
let lines = CTFrameGetLines(frame) as! [CTLine]
if let firstLine = lines.first {
  // First line text range.
  let range = CTLineGetStringRange(firstLine)
}

A ‘lines’ is CTLine array. it means each value is each lines
so you can manipulate string more easily. :-)