Alignment UITextView, care continues

I use UITextView where I want the text to be centered. However, this does not work completely. When you add a new line at the end of another line, which is not the last line, or by clicking on an empty line, the caret positions itself to the left of the text field, and when you start typing, it usually goes to the center. But sometimes it remains left-aligned, and the text itself is also left-aligned.

Creating a UITextView and adjusting the alignment programmatically or through a storyboard does not seem to matter. You can easily test it by adding a UITextView and setting the alignment to the center or to the right, as this seems to be the same problem.

A gif to illustrate the problem: http://i.stack.imgur.com/aZxrK.gif

+4
source share
1 answer

This is the closest I came to a solution for this:

I implement the method UITextViewDelegate textView:shouldChangeTextInRange:replacementText:and check if the entered text is a line break not at the end of the text. In this case, I add a space to it and put it in the text view. This leads to the fact that the carriage appears in the center, as it should be.

The only drawback to this is that you have a space that the user did not enter, and if he deletes it, then the carriage moves to the left again. However, it is better than nothing.

This is the code I used:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    BOOL isMidTextLinebreak = [text isEqualToString:@"\n"] && range.location != textView.text.length;
    if (isMidTextLinebreak) {
        NSMutableString *updatedText = [[NSMutableString alloc] initWithString:textView.text];
        text = [text stringByAppendingString:@" "];
        [updatedText insertString:text atIndex:range.location];
        textView.text = updatedText;

        // Set new caret position
        NSRange newRange = range;
        newRange.location += text.length;
        textView.selectedRange = newRange;
    }

    return !isMidTextLinebreak;
}
0

All Articles