Replace substring of NSAttributedString with another NSAttributedString

前端 未结 9 1153
野趣味
野趣味 2020-12-01 08:51

I want to replace a substring (e.g. @\"replace\") of an NSAttributedString with another NSAttributedString.

I am looking for a

9条回答
  •  感情败类
    2020-12-01 09:41

    I had to bold text in tags, here what I've done:

    - (NSAttributedString *)boldString:(NSString *)string {
        UIFont *boldFont = [UIFont boldSystemFontOfSize:14];
        NSMutableAttributedString *attributedDescription = [[NSMutableAttributedString alloc] initWithString:string];
    
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@".*?(.*?)<\\/b>.*?" options:NSRegularExpressionCaseInsensitive error:NULL];
        NSArray *myArray = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)] ;
        for (NSTextCheckingResult *match in myArray) {
            NSRange matchRange = [match rangeAtIndex:1];
            [attributedDescription addAttribute:NSFontAttributeName value:boldFont range:matchRange];
        }
        while ([attributedDescription.string containsString:@""] || [attributedDescription.string containsString:@""]) {
            NSRange rangeOfTag = [attributedDescription.string rangeOfString:@""];
            [attributedDescription replaceCharactersInRange:rangeOfTag withString:@""];
            rangeOfTag = [attributedDescription.string rangeOfString:@""];
            [attributedDescription replaceCharactersInRange:rangeOfTag withString:@""];
        }
        return attributedDescription;
    }
    

提交回复
热议问题