【问题标题】:how to change characters case to Upper in NSAttributedString如何在 NSAttributedString 中将字符大小写更改为大写
【发布时间】:2011-10-06 16:46:13
【问题描述】:

我想将包含 RTFD 的 NSAttributedString 转换为大写而不丢失现有字符和图形的属性。

谢谢,

【问题讨论】:

    标签: cocoa character uppercase nsattributedstring


    【解决方案1】:

    编辑:

    @fluidsonic 是正确的,原始代码不正确。下面是 Swift 的更新版本,它将每个属性范围内的文本替换为该范围内字符串的大写版本。

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

    原答案:

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

    这是做什么的:

    1. 制作输入属性字符串的可变副本。
    2. 从该字符串中获取所有属性并将它们放入一个数组中,以便以后使用。
    3. 使用内置的NSString 方法制作大写纯字符串。
    4. 重新应用所有属性。

    【讨论】:

    • 代码不正确。它可能会生成属性字符串,其中属性偏离了几个字符,甚至可能崩溃。该方法取决于初始字符串和大写字符串具有相同数量的字符。但根据documentation“不保证大小写转换是对称的或产生与原件长度相同的字符串。”。
    猜你喜欢
    • 2019-07-20
    • 2014-04-20
    • 2021-03-30
    • 2014-02-04
    • 2011-12-04
    • 2023-04-05
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    相关资源
    最近更新 更多