0

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.

Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72
  • Did you ever find a solution to this? I looked at the suggestion by @danhopwood below but it didn't make any difference. – Trey Sep 11 '14 at 21:52
  • TBH, I set this bug aside and moved on (I have the change to know that all my users will run 64bit devices). Hopefully it's fixed in iOS 8... – Guillaume Algis Sep 12 '14 at 08:19
  • Alright. Because I'm using the UITextView as a UILabel replacement I ended up just adding a space character to the beginning and end of the string. Seems to be working decently... – Trey Sep 12 '14 at 15:30
  • adding a space at the end of the text solves the issue. – akc Oct 01 '14 at 07:49

2 Answers2

1

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 :)

danhopwood
  • 123
  • 8
0

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

Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72