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

时间:2014-12-06 18:03:22

标签: ios cocoa-touch uitextview indentation auto-indent

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

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

2 个答案:

答案 0 :(得分:3)

虽然在这种情况下似乎OP实际上并没有寻找标准缩进,但我将其留给未来的求职者。

以下是在每个换行条目后自动添加缩进的方法。我已经根据最近类似的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;
}

答案 1 :(得分:2)

对于第一行,您必须编写此代码:

- (void)textViewDidBeginEditing(UITextView *)textView
{
    if ([textView.text isEqualToString:@""])
    {
        [textView setText:@"\t"];
    }
}