KAVIYA VENKAT
KAVIYA VENKAT

Reputation: 337

How to increase and decrease the height of the custom cell in TableViewCell

I am new to iphone development. I am using custom tableview cell. In that I have to increase and decrease the custom cell height based upon the condition. I have increased but while increasing the custom cell the main tableview also increases. I need to increase only the custom cell. Below I have shown the code what I have used.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"test"];
    if (!cell) {
        cell= [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"test"];
    }
    cell.backgroundColor = [UIColor blueColor];
    // Configure the cell...
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   int testvalue=1;
   if(testvalue == 1) {
      return 45;
   } else {
      return 100;
   }
}

Here I have attached screenshot.both main tableview and custom cell height is increasing. I don't want to increase main tableview cell height.

Upvotes: 4

Views: 1510

Answers (2)

Wasim
Wasim

Reputation: 1140

How I did was by Animating last view bottom constraints

func showOrHide() {
        UIView.animate(withDuration: 0.2) {
            if !self.isExpanded {
                self.heightConstraint?.constant = 0
                self.isExpanded = true

            } else {
                self.heightConstraint?.constant = 150
                self.isExpanded = false
            }
            self.contentView.layoutIfNeeded()
        }
    }

And then calling beginUpdates and endUpdates on tableview adjust cell height else sinking will not work

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
        cell.showOrHide()

        tableview.beginUpdates()
        tableview.endUpdates()
    }

Upvotes: 1

Vishal Sonawane
Vishal Sonawane

Reputation: 2693

First of all , I would highly recommend to use UITableViewAutomaticDimension for your tableView , so that you dont have to worry about the cell size.

Now, as per your requirement, you want to change cell size for certain conditions, so you can do something like this:

  • Take one base view in cell which will have all other views as subview.
  • Give height constraint to this base view and take outlet of that height constraint.
  • Now when you want to increase or decrease the height, simply change the height constarint constant value like your_height_constraint.constant = your_new_value

Hope this helps you.

Upvotes: 1

Related Questions