Fred Novack
Fred Novack

Reputation: 811

How to execute a method of a Custom Cell

I have a Custom Table View Cell that needs to pass a information to the heightForRowAtIndexPath method.

Each cell must answer what size it should have to heightForRowAtIndexPath method. How can I refer to that cell on specific indexPath and execute its getHeight method?

I used the [tableView dequeueReusableCellWithIdentifier:@"theCell" forIndexPath:indexPath]; but I get the error: "warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available." when I try do dequeue it.

Should I change my approach or is there a way to "ask" the cell which size it should have?

this is my Custom Cell getHeight method

-(CGFloat)getHeight{

    if(isCardOpen){
        //Calculate the size it should have based on its sub products
        //returning a test value for validation only
        return 253;
    }

    return 153;

}

this is my heightForRowAtIndexPath

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CardCell *cell = (CardCell*)[tableView dequeueReusableCellWithIdentifier:@"theCell" forIndexPath:indexPath];


    return [cell getHeight];


}

Upvotes: 0

Views: 57

Answers (3)

NRitH
NRitH

Reputation: 13893

You want auto-sizing cells. To do that, add the following lines to your view controller's viewDidLoad():

tableView.estimatedRowHeight = 85.0  // Use your own value here
tableView.rowHeight = UITableViewAutomaticDimension

You also have to ensure that each of your cell prototypes is able to calculate its own height explicitly. This means that you have to have autolayout constraints set up so that there's no vertical ambiguity.

Upvotes: 1

Vladyslav Zavalykhatko
Vladyslav Zavalykhatko

Reputation: 17354

It's not the best solution to let the cell rule its height.

Problem with your code is with

[tableView dequeueReusableCellWithIdentifier:@"theCell" forIndexPath:indexPath]

line. When you try to dequeue reusable cell, it tries to determine its height before, so you have cycle here. If you want the smallest workaround possible - change it to

[self cellForRawAtIndexPath]

Upvotes: 0

ObjectAlchemist
ObjectAlchemist

Reputation: 1127

You understand the usage wrong. Not the cell know it's height, the height will be given to a cell by the delegate function.

You need some kind of model that stores the information you need to create your layout (which cell should be at index X + which height should be at index X).

If you need a dynamic height you should read some blog posts about it, e.g.: https://www.raywenderlich.com/129059/self-sizing-table-view-cells

Upvotes: 0

Related Questions