ios - 拆分属性字符串并保留格式

标签 ios objective-c ios8 nsattributedstring

如何将现有的 NSAttributedString 根据预定义的分隔符进行划分,同时保持格式不变? componentsSeparatedByString 似乎不会对 NSAttributedString 进行操作。

我当前的解决方法在正确的点生成拆分,但只输出一个 NSString。从而丢失格式。

NSData *rtfFileData = [NSData dataWithContentsOfFile:path];
NSAttributedString *rtfFileAttributedString = [[NSAttributedString alloc] initWithData:rtfFileData options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSString *rtfFileString = [rtfFileAttributedString string];
NSString *importSeparator = @"###";
// Wish I could do this
// NSArray *separatedArray = [rtfFileAttributedString componentsSeparatedByString:importSeparatorPref];
NSArray *separatedArray = [rtfFileString componentsSeparatedByString:importSeparatorPref];
NSLog( @"Separated array: %@", separatedArray );

最佳答案

您可以使用拆分的非属性字符串来拆分属性字符串。一种选择是:

NSData *rtfFileData = [NSData dataWithContentsOfFile:path];
NSAttributedString *rtfFileAttributedString = [[NSAttributedString alloc] initWithData:rtfFileData options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSString *rtfFileString = [rtfFileAttributedString string];
NSString *importSeparator = @"###";
NSArray *separatedArray = [rtfFileString componentsSeparatedByString:importSeparatorPref];

NSMutableArray *separatedAttributedArray = [NSMutableArray arrayWithCapacity:separatedArray.count];
NSInteger start = 0;
for (NSString *sub in separatedArray) {
    NSRange range = NSMakeRange(start, sub.length);
    NSAttributedString *str = [rtfFileAttributedString attributedSubstringFromRange:range];
    [separatedAttributedArray addObject:str];
    start += range.length + importSeparator.length;
}

NSLog(@"Separated attributed array: ", separatedAttributedArray);

关于ios - 拆分属性字符串并保留格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250074/

相关文章:

ios map 捕捉到道路实现

ios - 使用结构体时不断收到 "Cannot assign to value: 'calculateBMI' is a method"

iphone - 我应该在 View Controller 中的哪里调用方法?

ios - Swift 3 Date 类型不作为自定义类的一部分进行编码

ios - 编码器 : unrecognized selector sent to instance

ios - 在 Storyboard之外创建一个 View Controller

Iphone:滚动时 UITableview 中的复选标记会混淆

ios - UISearchController:即使搜索栏为空也显示结果

ios - 无法使用 Testflight 进行内部测试的 'Start Testing'

ios - 同时显示 UIAlertView 和键盘