27

我想在 Objective-C 中计算 NSString 中的行数。

  NSInteger lineNum = 0;
  NSString *string = @"abcde\nfghijk\nlmnopq\nrstu";
  NSInteger length = [string length];
  NSRange range = NSMakeRange(0, length);
  while (range.location < length) {
      range = [string lineRangeForRange:NSMakeRange(range.location, 0)];
      range.location = NSMaxRange(range);
      lineNum += 1;
  }

有没有更简单的方法?

4

3 回答 3

46

苹果推荐这种方法:

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

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

文章。他们还解释了如何计算换行文本的行数。

于 2009-08-17T10:06:53.123 回答
37

好吧,一种效率不高但看起来不错(ish)的方式是

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

斯威夫特 4:

myString.components(separatedBy: .newlines)
于 2009-07-06T05:32:34.950 回答
5

如果要考虑文本的宽度,可以使用 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
}
于 2015-05-04T22:11:45.890 回答