最近开发用到富文本,在存储时,本人想到了用html保存,方便嘛,可是加载保存的html时却发现全部字号都被加大了,很诡异啊,以下是部分代码,求高手解惑
//创建一段带属性的字符串 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);
解决方案
40
看看输出的html文本,就知道原因了