4

テキストの強調表示を備えた機能がありますが、問題は改行も強調表示されることです。画像を参照してください。

ここに画像の説明を入力

以下は、強調表示に使用する関数です。

   -(void)setHighlight{

        //set highlighted

        __block BOOL textIsHighlited = YES;

        [self.attributedText enumerateAttributesInRange:[self selectedRange] options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
            if ([attrs valueForKey:@"NSBackgroundColor"] == Nil) {
                textIsHighlited = NO;
            }
        }];

        if (textIsHighlited) {
            [self.textStorage removeAttribute:NSBackgroundColorAttributeName range:[self selectedRange]];
        }else{
            [self.textStorage addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:[self selectedRange]];
        }
    }

簡単な解決策はありますか?改行の前で文字列を分割し、個別に強調表示する必要がありますか? また、文字列はユーザ​​ーが編集できるため、テキストの他の部分を編集しているときにテキストが壊れていないかどうかを確認するロジックが必要になることに注意してください。

提案をありがとう。

4

2 に答える 2

1

TextViewHighlighterを参照してください

基本的に、改行文字の範囲を検出し、それらの属性を作成する必要があります。NSBackgroundColorAttributeName: [UIColor clearColor]

NSMutableAttributedString *highlighedAttributedString = [[NSMutableAttributedString alloc] initWithString:self.text];
    [highlighedAttributedString addAttributes:@{NSForegroundColorAttributeName: self.textColor,
                                                NSBackgroundColorAttributeName: self.highlightedColor
                                                }
                                        range:NSMakeRange(0, self.text.length)];

    for (NSValue *rangeValue in rangeValues) {
        NSRange range = [rangeValue rangeValue];
        [highlighedAttributedString addAttributes:@{NSBackgroundColorAttributeName: [UIColor clearColor],
                                                    }
                                            range:range];
    }
于 2015-06-07T08:01:01.353 に答える