How to remove text from NSMutableAttributedString

2020-03-31 03:20发布

问题:

I need to remove some text from NSMutableAttributedString.

My code looks like this:

[attributedLabel setText:string afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString)
    {
        NSRange stringRange = NSMakeRange(0, [mutableAttributedString length]);
        NSRegularExpression *regexp = ParenthesisRegularExpression();
        UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:Size];
        DLog(@"%@",italicSystemFont.fontName);
        CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);
        [regexp enumerateMatchesInString:[mutableAttributedString string] options:0 range:stringRange usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
            if (italicFont) {
                [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:result.range];
                [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)italicFont range:result.range];
                CFRelease(italicFont);
            }
        }];

        return mutableAttributedString;
    }];

I would like to remove the parentheses from this mutableAttributedString.

Tried this:

[[attributedLabel.attributedText stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""];

But there is

no visible interface in NSAttributedString for stringByReplacingOccurrencesOfString.

How to I remove text from NSMutableAttributedString?

回答1:

Why do you even assume that NSMutableAttributedString responds to messages NSMutableString responds to? They don't inherit from one another. Instead you should read the documentation and use the mutableString method to get a mutable string instance to manipulate.



回答2:

Use the string method to return an NSString* from an NSAttributedString.

 NSString *newString = [attributedLabel.attributedText string];

Then you can use the normal NSString or NSMutableString methods on the resultant string and assign it back to your NSAttributedString when complete.



回答3:

Here's my take.

NSMutableAttributedString *source = attributedLabel.attributedText;
UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:Size];

    CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);

[[source  copy] enumerateAttributesInRange:NSMakeRange(0, source.length) options:NSAttributedStringEnumerationReverse  usingBlock:^(NSDictionary* attrs, NSRange range, BOOL *stop) {

    if ([[attrs valueForKey:kCTFontAttributeName] isEqualTo:(__bridge id)italicFont]) {
        [source deleteCharactersInRange:range];
    }

}];