1

我需要从 NSMutableAttributedString 中删除一些文本。

我的代码如下所示:

[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;
    }];

我想从这个 mutableAttributedString 中删除括号。

试过这个:

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

但是还有

no visible interface in NSAttributedString for stringByReplacingOccurrencesOfString.

如何从 NSMutableAttributedString 中删除文本?

4

3 回答 3

2

为什么你甚至假设NSMutableAttributedString响应消息NSMutableString响应?他们不会互相继承。相反,您应该阅读文档并使用该mutableString方法来获取可变字符串实例来操作。

于 2013-05-28T19:11:12.117 回答
0

使用该string方法NSString*NSAttributedString.

 NSString *newString = [attributedLabel.attributedText string];

然后,您可以对结果字符串使用普通的 NSString 或 NSMutableString 方法,并在完成后将其分配给您的NSAttributedString

于 2013-05-28T19:11:28.430 回答
0

这是我的看法。

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

}];
于 2015-07-24T22:29:57.150 回答