【问题标题】:iOS: how to change colour/font of some characters of a stringiOS:如何更改字符串中某些字符的颜色/字体
【发布时间】:2018-07-15 01:55:57
【问题描述】:

在我的应用程序中,我必须更改来自 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];

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

【问题讨论】:

  • 您如何定义“Andrew James”是发件人?它总是在那个特定的 span html 标记之间吗?
  • 是的,它总是在 span 标签之间
  • 由于该标签不会被“解释”而是被提交(在 Playground 上测试),我建议使用 rangeOfString:NSRegularExpression 找到它(如果它始终是同一个) , NSScanner 等,然后自己添加(或替换)一个 HTML 标记,为其定义颜色。
  • 你试过我的建议了吗?

标签: ios objective-c nsstring nsattributedstring


【解决方案1】:

我相信完成任务的最简单方法是在文本中使用内联 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(通过将样式附加到原始文本来创建)而不是原始文本,你应该很高兴。

【讨论】:

    【解决方案2】:
    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)];
    

    【讨论】:

    • 如果范围是动态的,我如何使用此代码,因为我的问题字符串来自 json 响应
    • 计算您的发件人在字符串中的位置并相应地调整范围。我没有足够的信息给你看。
    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 2012-12-16
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多