拆分归属字符串并保留格式 [英] Split Attributed String and Retain Formatting

查看:130
本文介绍了拆分归属字符串并保留格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在维护格式的同时,根据预定义的分隔符获取现有的NSAttributedString并将其划分?看起来componentsSeparatedByString似乎不会对NSAttributedString进行操作。

How can you take an existing NSAttributedString and divide it based on a predefined separator while maintaining formatting? It does not seem that componentsSeparatedByString will operate on an NSAttributedString.

我当前的解决方法会在正确的点生成拆分,但只输出NSString。因此失去格式。

My current workaround produces the splits at the correct points, but only outputs an NSString. Thus losing formatting.

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 );


推荐答案

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

You can make use of your split non-attributed string to split up the attributed string. One option would be:

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);

这篇关于拆分归属字符串并保留格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆