如何在NSAttributedString中将字符大小写改为Upper [英] how to change characters case to Upper in NSAttributedString
本文介绍了如何在NSAttributedString中将字符大小写改为Upper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将包含RTFD的NSAttributedString转换为大写,而不会丢失现有字符和图形的属性。
谢谢,
//将输入字符串的一个可变拷贝$($)$ {} b $ b NSMutableAttributedString * attrString = [inAttrString mutableCopy];
//创建一个数组来保存属性
NSMutableArray * attributes = [NSMutableArray array];
//将每一组属性添加到包含属性和范围的字典数组中
[attrString enumerateAttributesInRange:NSMakeRange(0,[attrString length])options:0 usingBlock:^ NSDictionary * attrs,NSRange range,BOOL * stop){
[attributes addObject:@ {@attrs:attrs,@range:[NSValue valueWithRange:range]}];
}];
//创建一个大写字符串
NSString * string = [[attrString string] uppercaseString];
//用大写字符替换字符
[attrString replaceCharactersInRange:NSMakeRange(0,[attrString length])withString:string];
//重新应用每个属性
for(NSDictionary * attribute in attributes){
[attrString setAttributes:attribute [@attrs] range:[attribute [@range ] rangeValue]];
}
return attrString;
}
这是做什么的:
- 制作输入属性字符串的可变副本。
- 从该字符串获取所有属性,并将其放入数组中,以便以后使用。
- 使用内置的
NSString
方法创建大写纯文本字符串。 - 应用所有属性。
I want to convert NSAttributedString containing RTFD to uppercase without losing attributes of existing characters and graphics.
Thanks,
解决方案
- (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:
- Makes a mutable copy of the input attributed string.
- Takes all the attributes from that string and puts them in an array so they can be used later.
- Makes an uppercase plain string using built-in
NSString
method. - Re-applys all the attributes.
这篇关于如何在NSAttributedString中将字符大小写改为Upper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文