How to count the number of lines in an Objective-C string (NSString)?

主宰稳场 提交于 2019-11-28 21:11:11
cobbal

well, a not very efficient, but nice(ish) looking way is

NSString *string = @"abcde\nfghijk\nlmnopq\nrstu";
NSInteger length = [[string componentsSeparatedByCharactersInSet:
                                [NSCharacterSet newlineCharacterSet]] count];

Swift 4:

myString.components(separatedBy: .newlines)
Loda

Apple recommends this method:

NSString *string;
unsigned numberOfLines, index, stringLength = [string length];

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

See the article. They also explain how to count lines of wrapped text.

If you want to take into account the width of the text, you can do this with TextKit (iOS7+):

func numberOfLinesForString(string: String, size: CGSize, font: UIFont) -> Int {
    let textStorage = NSTextStorage(string: string, attributes: [NSFontAttributeName: font])

    let textContainer = NSTextContainer(size: size)
    textContainer.lineBreakMode = .ByWordWrapping
    textContainer.maximumNumberOfLines = 0
    textContainer.lineFragmentPadding = 0

    let layoutManager = NSLayoutManager()
    layoutManager.textStorage = textStorage
    layoutManager.addTextContainer(textContainer)

    var numberOfLines = 0
    var index = 0
    var lineRange : NSRange = NSMakeRange(0, 0)
    for (; index < layoutManager.numberOfGlyphs; numberOfLines++) {
        layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)
        index = NSMaxRange(lineRange)
    }

    return numberOfLines
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!