murali krishna
murali krishna

Reputation: 7

How to find the height of the particular cell height in UITableViewcell?

I have a UITableView and the cells have different and random heights. The cells each contain a button, and when the button is pressed, I would like to get that particular cells height. How would I go about doing this?

Upvotes: 0

Views: 1711

Answers (4)

imDeveloper
imDeveloper

Reputation: 824

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

   //Here calculate your height
   return height;

}

Now Wherever you want to find cell height

first find indexpath

    NSIndexPath *indexPath = [tableView indexPathForCell:cell]

then find height of cell which is on that index path like below

   CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];

Upvotes: 2

Eimantas Kudarauskas
Eimantas Kudarauskas

Reputation: 73

You can try this.

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Calculate a height based on a cell
    if (!self.cutomCell)
    {
        self.cutomCell = [self.myTableView dequeueReusableCellWithIdentifier:@"CustomCell2"];
    }

    // Configure the cell
    self.cutomCell.introductionLabel.text   = self.infoArray[indexPath.row];


    // Layout the cell
    [self.cutomCell layoutIfNeeded];


    // Get the height for the cell
    CGFloat height = [self.cutomCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    return height;
}

Upvotes: 0

Patrick
Patrick

Reputation: 7185

I think you are after something like this;

-(IBAction)buttonPressed:(id)sender {

    UIButton *myButton = (UIButton *)sender;
    NSLog(@"%0.2f", myButton.superview.frame.size.height);

}

From the docs: "Views can embed other views and create sophisticated visual hierarchies. This creates a parent-child relationship between the view being embedded (known as the subview) and the parent view doing the embedding (known as the superview)."

Additionally, you will need to assign your button to the above method. This could be done in the interface builder, or can be done in cellForRowAtIndexPath which would look similar to this:

UIButton *heightButton = (UIButton *)[cell viewWithTag:1];
[heightButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];

Upvotes: 0

Saurabh Shukla
Saurabh Shukla

Reputation: 1398

heightForRowAtIndexPath is not used to get the height of particular cell. While this is DataSource method of UITableView and used to set the height of the UITableViewCell when it loads:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0;  // Set the cell height
}

Upvotes: 0

Related Questions