3

私のアプリにはUItextViewがあり、その入力ビューにはいくつかのボタンが付いたアクセサリビューがあります。

既に入力されているテキストを変更して、テキストに下線を引こうとしています。正常に動作しますが、変換後にフォントとフォントサイズが失われます。

これが私がやっていることです:

NSRange selectedRange = [self.commentsTextView selectedRange];

            NSDictionary *currentAttributesDict = [self.commentsTextView.textStorage attributesAtIndex:selectedRange.location
                                                                            effectiveRange:nil];

            NSDictionary *dict;

            if ([currentAttributesDict objectForKey:NSUnderlineStyleAttributeName] == nil ||
                [[currentAttributesDict objectForKey:NSUnderlineStyleAttributeName] intValue] == 0) {

                dict = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInt:1]};

            }
            else{
                dict = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInt:0]};
            }

            [self.commentsTextView.textStorage beginEditing];
            [self.commentsTextView.textStorage setAttributes:dict range:selectedRange];
            [self.commentsTextView.textStorage endEditing];
4

1 に答える 1

2

の値のみを持つ辞書を使用して、その範囲のテキストの属性を設定していますNSUnderlineStyleAttributeName

if... else構造体では、 fontfont sizeに必要な値をNSUnderlineStyleAttributeName指定するだけでなく、.dict

以前にフォントフォント サイズをどのように設定しましたか?

概要セクションUITextViewのAppleのドキュメントから:

iOS 6 以降では、このクラスは attributedText プロパティを使用して複数のテキスト スタイルをサポートします。(スタイル付きテキストは、以前のバージョンの iOS ではサポートされていません。) このプロパティに値を設定すると、属性付き文字列で提供されるスタイル情報がテキスト ビューで使用されます。font、textColor、および textAlignment プロパティを使用してスタイル属性を設定することはできますが、これらのプロパティはテキスト ビュー内のすべてのテキストに適用されます。

https://developer.apple.com/library/ios/documentation/uikit/reference/uitextview_class/Reference/UITextView.html

テキストの特定の範囲に属性を設定すると、新しい属性のみを使用して、その範囲に以前存在していたスタイルが上書きされます。

于 2014-04-01T20:39:31.627 に答える