代码之家  ›  专栏  ›  技术社区  ›  Abhinandan Pratap rckoenes

iOS:如何更改字符串中某些字符的颜色/字体

  •  1
  • Abhinandan Pratap rckoenes  · 技术社区  · 6 年前

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

    > "<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];
    

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

    3 回复  |  直到 6 年前
        1
  •  1
  •   Suraj Rao Aditya Agrawal    4 年前

    此外,您可以按如下方式使用它。

    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;
    
        2
  •  0
  •   Ryan Heitner    6 年前
    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)];
    
        3
  •  0
  •   Milan Nosáľ    6 年前

    我认为完成任务最简单的方法是在文本中使用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 (通过将样式附加到原始文本中创建)而不是原始文本,您应该可以继续。