I want to convert NSAttributedString containing RTFD to uppercase without losing attributes of existing characters and graphics.
Thanks,
Attributed strings are character strings that have attributes for individual characters or ranges of characters. Attributes provide traits like visual styles for display, accessibility for guided access, and hyperlink data for linking between data sources.
First create an NSMutableAttributedString with a new font attribute. You don't use textView. text . Then append another attributed string that doesn't have any attributes set.
The term "text attributes" refers to all of the font, style, alignment, and other formatting associated with a given character or series of characters.
EDIT:
@fluidsonic Is correct that the original code is incorrect. Below is an updated version in Swift, that replaces the text in each attribute range with an uppercased version of the string in that range.
extension NSAttributedString {
func uppercased() -> NSAttributedString {
let result = NSMutableAttributedString(attributedString: self)
result.enumerateAttributes(in: NSRange(location: 0, length: length), options: []) {_, range, _ in
result.replaceCharacters(in: range, with: (string as NSString).substring(with: range).uppercased())
}
return result
}
}
Original answer:
- (NSAttributedString *)upperCaseAttributedStringFromAttributedString:(NSAttributedString *)inAttrString {
// Make a mutable copy of your input string
NSMutableAttributedString *attrString = [inAttrString mutableCopy];
// Make an array to save the attributes in
NSMutableArray *attributes = [NSMutableArray array];
// Add each set of attributes to the array in a dictionary containing the attributes and range
[attrString enumerateAttributesInRange:NSMakeRange(0, [attrString length]) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
[attributes addObject:@{@"attrs":attrs, @"range":[NSValue valueWithRange:range]}];
}];
// Make a plain uppercase string
NSString *string = [[attrString string]uppercaseString];
// Replace the characters with the uppercase ones
[attrString replaceCharactersInRange:NSMakeRange(0, [attrString length]) withString:string];
// Reapply each attribute
for (NSDictionary *attribute in attributes) {
[attrString setAttributes:attribute[@"attrs"] range:[attribute[@"range"] rangeValue]];
}
return attrString;
}
What this does:
NSString
method.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With