EDIT:
@fluidsonic It is true that the source code is incorrect. The following is an updated version in Swift that replaces the text in each attribute range with an uppercase version of a 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 does it do:
- Creates a modified copy of the string associated with the input.
- Takes all the attributes from this string and puts them in an array so that they can be used later.
- Makes a simple string string in uppercase using the built-in
NSString method. - Reapplies all attributes.
spudwaffle
source share