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

后端 未结 3 1729
执笔经年
执笔经年 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: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
    }
    

提交回复
热议问题