iOS: 如何改变字符串中某些字符的colour/font

iOS: how to change colour/font of some characters of a string

在我的应用程序中,我必须更改来自 JSON 响应

string 的一部分的字体
> "<span class=\"drop_data_user\">Andrew James</span> liked your comment
> \"hiiiiiiiiiiiiiii\" that you posted."

将其转换为属性字符串我正在使用以下代码

NSAttributedString *attr = [[NSAttributedString alloc] initWithData:[NotificationTxt dataUsingEncoding:NSUTF8StringEncoding]
                                                                options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                          NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)}
                                                     documentAttributes:nil
                                                                  error:nil];

我要更改发件人的字体颜色

我相信完成任务的最简单方法是在文本中使用 CSS 内联,然后像你那样解析 HTML 也会改变颜色(我使用 Swift 语法,但我相信您可以轻松地将其转换为 ObjC):

let text = "<span class=\"drop_data_user\">Andrew James</span> liked your comment \"hiiiiiiiiiiiiiii\" that you posted."
let colouredAuthorText = "\(text)<style>.drop_data_user { color: #FEB600; }</style>"

然后只需解析 colouredAuthorText(通过将样式附加到原始文本创建的)而不是原始文本,您应该可以开始了。

NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:@"My String"];
[attrS addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
[attrS addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(3, 6)];

self.myLabel.attributedText = attrS;

字体使用

[attrS addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, 3)];

另外,您还可以按如下方式使用。

NSString *dateString = [NSString stringWithFormat:@"%@%@", @"Teslimat: ", selectedReservationModel.DateLabel];
        NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString: dateString];
        [attrS addAttribute:NSFontAttributeName value:[GenericUtility getOpenSansBoldFontSize:12] range:NSMakeRange(0, 8)];
        [attrS addAttribute:NSFontAttributeName value:[GenericUtility getOpenSansRegularFontSize:12] range:NSMakeRange(9, selectedReservationModel.DateLabel.length)];
        lblDeliveryDate.attributedText = attrS;