iphoneiosuitableviewheightforrowatindexpath

how to obtain the UITableViewCell within heightForRowAtIndexPath?


How does one obtain the UITableViewCell when within the heightForRowAtIndexPath method, i.e. given the indexPath?

(then I could access the content views I have created to add their heights up)

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  // How to get the UITableViewCell associated with this indexPath?
}

thanks

EDIT: In fact is there really a valid way to do this? When I put some NSLog statements it seems that heightForRowAtIndexPath it called several times before the calls to cellForRowAtIndexPath (which is where I set up the UILabels in the cell)? This kind implies that I may be tried to use a technique that will not work, i.e. I was hoping in heightForRowAtIndexPath to access the already created labels in each cell to get their heights and add them together for the overall cell row height, HOWEVER if they haven't been set up yet (within cellForRowAtIndexPath) then I guess my approach can't really work?


Solution

  • For iOS8:

    override func viewDidLoad() {
            super.viewDidLoad()
    
            self.tableView.estimatedRowHeight = 80
            self.tableView.rowHeight = UITableViewAutomaticDimension
        }
    

    OR

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
                return UITableViewAutomaticDimension
    
        }
    

    But for iOS7, the key is calculate the height after autolayout,

    func calculateHeightForConfiguredSizingCell(cell: GSTableViewCell) -> CGFloat {
            cell.setNeedsLayout()
            cell.layoutIfNeeded()
            let height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height + 1.0
            return height
    
        }
    

    Note:

    1) If multiple lines labels, don't forget set the numberOfLines to 0.

    2) Don't forget label.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds)