cyril
cyril

Reputation: 3005

How can I increase the height of a cell if I am using UITableViewAutomaticDimension?

I have a tableview which uses UITableViewAutomaticDimension to calculate cell height. I am trying to make the cells expand when tapped a la Twitter but I'm having trouble with the cell expansion even though cell returning to normal size works fine. I want each cell to expand by a constant value (e.g. 50) but I can't seem to grab the selected cell height and add 50 to it since heightForRowAtIndexPath is called before cellForRowAtIndexPath. Anyone have any insight on what I can do?

Here's my code:

var selectedIndexPath: NSIndexPath? = nil

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if !hasImageAtIndexPath(indexPath) {
        var cell = tableView.cellForRowAtIndexPath(indexPath) as! TimelineTableViewCell
        } else {
        var cell = tableView.cellForRowAtIndexPath(indexPath) as! TimelineTableViewCellImage
        }
        switch selectedIndexPath {
        case nil:
            selectedIndexPath = indexPath
        default:
            if selectedIndexPath! == indexPath {
                selectedIndexPath = nil
            } else {
                selectedIndexPath = indexPath
            }
        }
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let smallHeight: CGFloat = UITableViewAutomaticDimension

//Here is where I'm having trouble. Cells have a height of 50 and not current height +50
            let expandedHeight: CGFloat = UITableViewAutomaticDimension+50
            let ip = indexPath
            if selectedIndexPath != nil {
                if ip == selectedIndexPath! {
                    return expandedHeight
                } else {
                    return smallHeight
                }
            } else {
                return smallHeight
            }
        }

Upvotes: 0

Views: 298

Answers (1)

Schemetrical
Schemetrical

Reputation: 5536

-tableView:heightForRowAtIndexPath: should always return UITableViewAutomaticDimension. In fact you can just do self.tableView.rowHeight = UITableViewAutomaticDimension.

To make your cell higher, you change the cell constraints in -tableView:cellForRowAtIndexPath: so either your content constraint is higher or your cell height constant constraint is taller.

Upvotes: 1

Related Questions