29,027
社区成员
发帖
与我相关
我的任务
分享
//创建一段带属性的字符串
NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc]initWithString:@"What can I do?中文测试"];
[attriString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:24.0]
range:NSMakeRange(0, attriString.length)];
[attriString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(0, attriString.length)];
[attriString addAttribute:NSBackgroundColorAttributeName
value:[UIColor grayColor]
range:NSMakeRange(0, 2)];
[attriString addAttribute:NSBackgroundColorAttributeName
value:[UIColor greenColor]
range:NSMakeRange(2, attriString.length-2)];
[attriString addAttribute:NSUnderlineStyleAttributeName
value:@1
range:NSMakeRange(0, attriString.length)];
//将带属性的字符串转换成html以便存储
NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [attriString dataFromRange:NSMakeRange(0, attriString.length) documentAttributes:exportParams error:nil];
NSString * test= [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",test);
//将刚刚转换的html字符串转换成NSAttibutedString
//把font-size中的单位去掉就正常,不去掉的话,转成NSAttibutedString时会加大字号
//不知道为什么呀?就是这个很郁闷
test=[test stringByReplacingOccurrencesOfString:@"pt" withString:@""];
NSData *htmltest = [test dataUsingEncoding:NSUTF8StringEncoding];
// Create the HTML string
NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSAttributedString *test2 = [[NSAttributedString alloc] initWithData:htmltest options:importParams documentAttributes:nil error:nil];
NSLog(@"%@",test2);