jspinks
jspinks

Reputation: 133

Counting lines in Swift

Apple's Text Layout Programming Guide contains the following fragment of Objective-C code to count the number of lines in an NSString.

NSString *string;
unsigned numberOfLines, index, stringLength = [string length];
for (index = 0, numberOfLines = 0; index < stringLength; numberOfLines++)
    index = NSMaxRange([string lineRangeForRange:NSMakeRange(index, 0)]);

What would the Swift equivalent be using native String?

Upvotes: 1

Views: 3430

Answers (2)

telenaut
telenaut

Reputation: 390

here it is (just a plain translation of the guide you posted):

func countLines(textView: UITextView) -> Int {
    let layoutManager = textView.layoutManager
    var numberOfLines = 0
    var index = 0
    var lineRange = NSRange()
    var numberOfGlyphs = layoutManager.numberOfGlyphs
    for(numberOfLines, index; index < numberOfGlyphs; numberOfLines++){
        layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)
        index = NSMaxRange(lineRange);
    }
    return numberOfLines
}

or, if you need a specific range in your textcode (like me):

func countLinesInRange(textView: UITextView, range: NSRange) -> Int{
    let layoutManager = textView.layoutManager
    var numberOfLines = 0
    var index = range.location
    var lineRange = range
    var numberOfGlyphs = layoutManager.numberOfGlyphs
    for(numberOfLines, index; index < range.location+range.length; numberOfLines++){
        layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)
        index = NSMaxRange(lineRange);
    }
    return numberOfLines
}

Upvotes: 0

jspinks
jspinks

Reputation: 133

This is the solution to the problem I found so I will leave it here in case someone else finds it useful.

var text = "Line 1\nLine 2\nLine 3"
for var range = text.startIndex...text.startIndex; range.endIndex < text.endIndex;
        range = range.endIndex..<range.endIndex {
    range = text.lineRangeForRange(range)
}

Upvotes: 1

Related Questions