11

既存の文字やグラフィックの属性を失うことなく、RTFD を含む NSAttributedString を大文字に変換したいと考えています。

ありがとう、

4

1 に答える 1

13

編集:

@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. すべての属性を再適用します。

于 2011-07-17T23:32:41.180 に答える