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?
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.
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.
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];
}
}];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.