当用户键入新行时,如何向UITextView添加自动缩进? [英] How can I add auto indentation to UITextView when user type new line?

查看:188
本文介绍了当用户键入新行时,如何向UITextView添加自动缩进?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户键入新行时,如何向 UITextView 添加自动缩进?示例:

How can I add auto indentation to UITextView when user type new line? Example:

line1
  line2 <user has typed "Enter">
  <cursor position>
    line3 <user has typed "Enter">
    <cursor position>


推荐答案

虽然看起来好像OP

这里是如何自动添加缩进每次换行之后。我已根据我最近有关在每个换行自动添加项目符号的答案修改此答案。

Here's how you can automatically add an indent after every newline entry. I've adapted this answer from my similar recent answer about automatically adding bullet points at every newline.

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

    // If the replacement text is "\n" thus indicating a newline...
    if ([text isEqualToString:@"\n"]) {

        // If the replacement text is being added to the end of the
        // text view's text, i.e. the new index is the length of the
        // old text view's text...
        if (range.location == textView.text.length) {
            // Simply add the newline and tab to the end
            NSString *updatedText = [textView.text stringByAppendingString:@"\n\t"];
            [textView setText:updatedText];
        }

        // Else if the replacement text is being added in the middle of
        // the text view's text...
        else {

            // Get the replacement range of the UITextView
            UITextPosition *beginning = textView.beginningOfDocument;
            UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
            UITextPosition *end = [textView positionFromPosition:start offset:range.length];
            UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];

            // Insert that newline character *and* a tab
            // at the point at which the user inputted just the
            // newline character
            [textView replaceRange:textRange withText:@"\n\t"];

            // Update the cursor position accordingly
            NSRange cursor = NSMakeRange(range.location + @"\n\t".length, 0);
            textView.selectedRange = cursor;

        }

        // Then return "NO, don't change the characters in range" since
        // you've just done the work already
        return NO;
    }

    // Else return yes
    return YES;
}

这篇关于当用户键入新行时,如何向UITextView添加自动缩进?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆