OStack程序员社区-中国程序员成长平台

标题: ios - html字符串转换为属性字符串与\U00002028\n ios [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 20:50
标题: ios - html字符串转换为属性字符串与\U00002028\n ios

Html 字符串从服务器获取我尝试转换为属性字符串。 使用

NSAttributedString *attributedString = [[NSAttributedString alloc]
                                        initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                                        options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding] }
                                        documentAttributes: nil
                                        error: nil
                                        ];

具有\U00002028\n 的属性字符串会导致显示字符串在文本中出现间距和换行。如何才能删除这样的东西。



Best Answer-推荐答案


从 NSMutableAttributedString 中修剪前导和尾随空格

NSString * _strAchievementMsg= @"  Hi Test the White space    ";

NSString * htmlString = [NSString stringWithFormat"<html><div>%@</div></html>",_strAchievementMsg];

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]
                                        initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                                        options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding] }
                                        documentAttributes: nil
                                        error: nil
                                        ];
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSRange range           = [attString.string rangeOfCharacterFromSet:charSet];
while (range.length != 0 && range.location == 0)
{
    [attString replaceCharactersInRange:range withString""];
    range = [attString.string rangeOfCharacterFromSet:charSet];
}

// Trim trailing whitespace and newlines.
range = [attString.string rangeOfCharacterFromSet:charSet
                                          options:NSBackwardsSearch];
while (range.length != 0 && NSMaxRange(range) == attString.length)
{
    [attString replaceCharactersInRange:range
                             withString""];
    range = [attString.string rangeOfCharacterFromSet:charSet
                                              options:NSBackwardsSearch];
}

关于ios - html字符串转换为属性字符串与\U00002028\n ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37915304/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4