ios - 修剪属性字符串的最后两行
问题描述
如何删除此 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" 结尾。谢谢
解决方案
我建议作为最佳解决方案:
-(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,它也不会中断
推荐阅读
- cellpadding - 嵌套滚动表中的单元格填充
- python - 如何为跨平台静音麦克风?
- django - Django - 从数据库中手动删除应用程序
- azure-devops - Azure DevOps,查询以显示从一个 Epic 移动到另一个 Epic 的所有功能
- ssh - Pycharm Pro Remote Server : Settings->Deployment->Agent-> Web Server URL: 它有什么作用?未设置,仍然有效
- perl - Perl:将公式转换为 Perl 代码 它应该是什么样的?
- reactjs - Monorepos,图像未在不同的基本路径中加载
- netsuite - Suitescript 2.0 从 Suitelet 文件字段中获取文件内容并在预定脚本中使用数据
- flutter - Flutter 如何禁用 WebView 中的弹出窗口?
- mongodb - MongoDB $或表现得像 $and