Question

I'd like to have a simple UITextView which automatically resizes to fit its content.

With AutoLayout this is quite straightforward: I add the UITextView to my view, set two contraints to anchor the UITextView in the top-left corner, disable scrolling and that's it.

IB setup

The expected behavior is that the green text view resize its frame each time I type in a character. But this works only partially: for some text, the text view decide that it will render it over two line, instead of just adding the new character at the end of the current line:

Examples of text rendering in a UITextView

I'm guessing this is related to the new TextKit framework, and I played with NSLayoutManager's and NSTextContainer's properties to try to control this behavior, but to no avail.

Note also that if I "hardcode" the width of the text view (for example with a width contraint), the characters are correctly appended at the end of the line, but then I lose the horizontal autoresizing property of the text view.

How can I indicate to the UITextView that I don't want it to break line?

EDIT: After further testing, the bug only seems to appear on 32bits archs.

Was it helpful?

Solution 2

This is apparently now fixed in iOS 8. (Xcode 6.0.1 (6A317)).

OTHER TIPS

A bit of a hack (and hoping it's fixed in iOS8) but the following stopped it from happening:

- (void)textViewDidChange:(UITextView *)textView {

    // uber hack to stop characters from jumping to the line below
    if (textView.text.length == 1 && ![textView.text isEqualToString:@" "]) {
        NSRange cursorPosition = [textView selectedRange];
        textView.text = [NSString stringWithFormat:@"%@ ", textView.text];
        textView.selectedRange = cursorPosition;
    }

    [textView invalidateIntrinsicContentSize];
}

Annoyed me for a while so hope that helps someone else :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top