简体   繁体   中英

Dynamically size UITableViewCell's height

I have a UITableViewCell with multiple items inside. (Not just a textView so I cant follow this option.) I'm trying to dynamically size it's height based on the content it has inside.

The heights I will be changing, are a UITextView and a UIView. The textView will constantly be changing (at another method, if you'd like, I can post it). And the UIView will change if the user clicks a button:

Here is my code:

- (void)viewDidLoad
{
   self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (IBAction)thisButton:(id)sender
{   
    CGRect frame = self.myView.frame;
    frame.size.height = 50;
    frame.size.width = self.myView.frame.size.width;

    self.myView.frame = frame;

    // update 'myView's constraint
    self.viewHeight.constant = self.myView.frame.size.height;

    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [myTableView reloadData];
}

Problem:

  • What happens is, when I press the button, the UIView's height gets updated, but then everything else in the cell gets moved up, and the cell stays the same size.

  • When the UITextView's height changes, it doesn't pull everything else down, and the cells height stays the same. Though the textView's height does change and it just goes over everything else.

Constraints:

On the UITextView I have 3 constraints - 2 on each side, and 1 on top. The UIView has 3 constraints - 2 on each side, and 1 on the bottom. I then have a constraint connecting the UIView to the textView.

You can dynamically manage UITableViewCell size by calculating a max height of your internal views:

NSArray *array = [[NSArray alloc] initWithArray:@[view1, view2, view3]];

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    __block CGFloat maxHeight;
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIView *view = obj;
        if (view.bounds.size.height > maxHeight) {
            maxHeight = view.bounds.size.height;
        }
    }];

    return maxHeight;
}

Then in the end of your method that changes view's dimensions you must call [self.tableView reloadData]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM