Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update UITableViewCell height because of text entered into UITextView

I have different examples where we can update the UITableViewCell height based on growing UITextView which actually is working for me. The issue which I am facing is, I have more subviews below UITextView inside a UITableViewCell. This way, the cell's height updates but the position of the subviews remain fixed which causes overlap of UITextView and the subviews. Just to mention, I am not using auto layout.
How do I fix this ?
These are the three screenshots which will help in understanding my issue :

1. Before TextView is shown :

enter image description here

2. After TextView is shown :

enter image description here

3. After text is entered :

enter image description here

like image 907
Nitish Avatar asked Dec 09 '15 18:12

Nitish


3 Answers

I'm assuming you are using auto layout for this cell (but we could use a code example or Xcode screenshot to help you more specifically). If you are using auto layout, you'll want to make sure that:

  1. You have a constraint between the UITextView and the other UIView subviews below it in the cell
  2. The other UIView subviews are eventually constrained to the bottom of the cell.
like image 153
Chris Ricca Avatar answered Nov 13 '22 11:11

Chris Ricca


Because UITableViewCells are reused, you will find that when adding objects to the contentView, those objects will also be reused without being removed, leading to overlapping subviews. The way around this it to start your cellForRowAtIndexPath with the following code:

 static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    for (UIView * view in [cell.contentView subviews]) {
//        clears the cell before reusing
        [view removeFromSuperview];
    }

Hope this helps.

like image 3
mylogon Avatar answered Nov 13 '22 12:11

mylogon


Are you using auto layout? I have done this before several times with UITableViewCells though it’s mainly been with UILabel and not UITextView.

Your problem might be resolved with auto layout. You layout all your subviews (inside of UITableViewCell) relative to each other. If one view (i.e. UITextView) changes size the other views will then adjust relative to that view. Here are a few useful links.

This isn’t specific to UITableViewCell but has a lot of good examples of various scenarios. Stanford University Developing iOS 7 Apps: Lecture 9 - Animation and Autolayout https://www.youtube.com/watch?v=r1sc7NI6-wo

like image 2
xdeleon Avatar answered Nov 13 '22 10:11

xdeleon