7

次のような機能を実装する必要があるアプリを作成しています。

1) テキストビューに書き込む

2) テキストビューからテキストを選択

3) ユーザーが選択したテキストに太字、斜体、下線の機能を適用できるようにします。

NSMutableAttributedString を使用して実装を開始しました。太字と斜体で機能しますが、テキストビューのテキストを選択したテキストのみに置き換えます。

-(void) textViewDidChangeSelection:(UITextView *)textView
{
       rangeTxt = textView.selectedRange;
       selectedTxt = [textView textInRange:textView.selectedTextRange];
       NSLog(@"selectedText: %@", selectedTxt);

}

-(IBAction)btnBold:(id)sender
{

    UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize];

    NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];

    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedTxt attributes:boldAttr];

    txtNote.attributedText = attributedText;

}

この機能を実装するのを手伝ってくれる人はいますか?

前もって感謝します。

4

1 に答える 1

1

didChangeSelectionこの目的で使用しないでください。shouldChangeTextInRange代わりに使用してください。

これは、属性付き文字列を新しいものに設定すると、特定の場所のテキストが置き換えられないためです。全文を新しいテキストに置き換えます。テキストを変更する位置を特定するには範囲が必要です。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

     NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText];

    NSRange selectedTextRange = [textView selectedRange];
    NSString *selectedString = [textView textInRange:textView.selectedTextRange];

    //lets say you always want to make selected text bold
    UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize];

    NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];

    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedString attributes:boldAttr];

   // txtNote.attributedText = attributedText; //don't do this

    [textViewText replaceCharactersInRange:range withAttributedString:attributedText]; // do this

    textView.attributedText = textViewText;
    return false;
}
于 2014-10-28T12:33:21.043 に答える