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

时间:2015-05-24 21:55:55

标签: ios uitableview swift

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
            }
        }

1 个答案:

答案 0 :(得分:1)

-tableView:heightForRowAtIndexPath: 应始终返回UITableViewAutomaticDimension 。实际上你可以做self.tableView.rowHeight = UITableViewAutomaticDimension

要使您的单元格更高,请更改-tableView:cellForRowAtIndexPath:中的单元格约束,以便内容约束更高或单元格高度常量约束更高。

相关问题