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

后端 未结 3 1725
执笔经年
执笔经年 2020-12-14 16:26

I want to count the lines in an NSString in Objective-C.

  NSInteger lineNum = 0;
  NSString *string = @\"abcde\\nfghijk\\nlmnopq\\nrstu\";
  NSInteger lengt         


        
相关标签:
3条回答
  • 2020-12-14 16:52

    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)
    
    0 讨论(0)
  • 2020-12-14 16:55

    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
    }
    
    0 讨论(0)
  • 2020-12-14 16:59

    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.

    0 讨论(0)
提交回复
热议问题