How can I add automatic indentation to a UITextView when the user enters a new line?

How do I add automatic indentation to UITextView

when the user enters a new line? Example:

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

      

+3


source to share


2 answers


While it seems that the OP is not really looking for standard indentation in this case, I leave that to future seekers for answers.

Here you can automatically add indentation after each newline entry. I adapted this answer from my similar recent answer on how to automatically add markers on every new line .



- (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 text, i.e. the new index is the length of the
        // old text view 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 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;
}

      

+3


source


For the first line, you will need to write this code:



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

      

+2


source







All Articles