marshy101
marshy101

Reputation: 594

Re-enable UITextView scrolling after it expands, with AutoLayout, to a specified height

I understand there are some similar posts but they don't seem to work for me.

I have a uitextview that I want to behave similar to messenging apps.

I used autolayouts and [textview setScrollEnabled:NO] to allow the uitextview to expand dynamically above the keyboard. Of course, it grows till it reaches the top of the screen. When it stops growing you cant see any additional text.

I tried to find the height where it stop growing inside the textViewDidChange and called [textView setScrollEnabled:YES], but it shrinked back the initial size before it grew.

How can i enable the scrolling when it reaches a certain height or cant grow anymore?

Upvotes: 4

Views: 2374

Answers (4)

chents
chents

Reputation: 403

Best solution i've found till now was to leave scrolling enabled and changing textview's height according to it's content size.

Looks something like this:

- (void)textViewDidChange:(UITextView *)textView
{
    self.consTextViewHeight.constant = MIN(MAX_HEIGHT, textView.contentSize.height + textView.textContainerInset.top);
}

Upvotes: 8

rdelmar
rdelmar

Reputation: 104092

Add a height constraint to the text view when it reaches the desired distance from the top of the screen. I've done it like this,

-(void)textViewDidChange:(UITextView *)textView {
    if (textView.scrollEnabled == NO) {
        if (textView.frame.origin.y < 50) {
            [textView addConstraint:[NSLayoutConstraint constraintWithItem:textView attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:textView.frame.size.height]];
            textView.scrollEnabled = YES;
        }
    }
}

When the text view grows to within 50 points from the top of the view, it gets a height constraint equal to its present height.

Upvotes: 0

pronebird
pronebird

Reputation: 12260

it's a research and here the lead for you.

  1. Subclass your text view.

  2. Monitor contentSize changes, probably there is a setter you can override or simply KVO can work.

  3. Create text view delegate that will ping your controller back to update autolayout constraints.

  4. When contentSize reaches your defined maximum, simply clamp the value and let text view scroll naturally.

Upvotes: 0

Miknash
Miknash

Reputation: 7948

Have you tried to setContentSize for textView? You can do that in viewDidLayoutSubviews if you want to wait for autolayout to finish.

Here is helpful link : how set content size of textView's Scrollview immediately when user starts scrolling or when tap on textview

NOTE: this should be a comment, but I don't have enough reputation for that...

Upvotes: 1

Related Questions