how to change the height of a single cell when clicked?

后端 未结 1 664
囚心锁ツ
囚心锁ツ 2020-12-13 11:23

I have to resize a single row of my tableView when clicked. How I can do this? Anybody could help me?

My view controller class:

class DayViewControl         


        
相关标签:
1条回答
  • 2020-12-13 12:06

    First you have to keep track of the indexPath of currently selected cell in a property:

    var selectedCellIndexPath: NSIndexPath?
    

    It should be an optional, because you can have no cell selected. Next lets declare heights for selected and unselected state (change the values to whatever you want):

    let selectedCellHeight: CGFloat = 88.0
    let unselectedCellHeight: CGFloat = 44.0
    

    Now you have to implement tableView(_:, heightForRowAtIndexPath:):

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if selectedCellIndexPath == indexPath {
            return selectedCellHeight
        }
        return unselectedCellHeight
    }
    

    Now in your tableView(_:, didSelectRowAtIndexPath:) method you have to check wether the selected row or an unselected row has been tapped:

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath {
            selectedCellIndexPath = nil
        } else {
            selectedCellIndexPath = indexPath
        }
    
        tableView.beginUpdates()
        tableView.endUpdates()
    
        if selectedCellIndexPath != nil {
            // This ensures, that the cell is fully visible once expanded
            tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .None, animated: true)
        }
    }
    

    The beginUpdates() and endUpdates() calls are giving you an animated height change.

    If you want to change the duration of the height change animation you can wrap the beginUpdates() and endUpdates() calls in an animation block UIView.animationWithDuration(...) and set it to whatever value you want.

    You can check out this sample project which demonstrates this code in action.

    0 讨论(0)
提交回复
热议问题