首页 > 解决方案 > 修剪属性字符串的最后两行

问题描述

如何删除此 NSAttributedString 的最后两行?

NSString *exampleString = @"line 1\nline 2\nline 3\nline 4"
NSAttributedString *as = [NSAttributedString alloc] int];
[as setString:exampleString];
[self removeLastTwoLinesOfAttributedString:as];
NSLog(@"%@",as);

-(void)removeLastTwoLinesOfAttributedString:(NSAttributedString *)string {
   //some code here
}

在此示例中,我想以 @"line 1\nline 2" 结尾。谢谢

标签: iosobjective-cnsattributedstring

解决方案


我建议作为最佳解决方案:

-(NSAttributedString *)removeLastTwoLinesOfAttributedString:(NSAttributedString *)aString {

    if (aString.length == 0) {
        return aString
    }

    NSString *string = [aString string];

    unsigned numberOfLines, index, stringLength = [string length];
    NSRange rangeOfLastTwoLines = NSMakeRange(aString.length - 1, 0);

    for (index = stringLength-1, numberOfLines = 0; index >= 0 && numberOfLines < 2; numberOfLines++) {
        NSRange rangeOfLine = [string lineRangeForRange:NSMakeRange(index, 0)];
        rangeOfLastTwoLines = NSUnionRange(rangeOfLastTwoLines, rangeOfLine);
        index -= rangeOfLine.length;
    }

    return [aString attributedSubstringFromRange:NSMakeRange(0, rangeOfLastTwoLines.location)];
}

这样做的好处是可以使用任何换行符,而不仅仅是“\n”,并且它使用 Apple 首选的方法来检测行,请参阅

如果最后两行小于 2,它也不会中断


推荐阅读