How to animate the height change of an section header in UITableView?

前端 未结 4 915
再見小時候
再見小時候 2020-12-13 20:48

I\'ve implemented this method to return the section header height. However, when the height for the section changes, it happens immediately without animation.

4条回答
  •  隐瞒了意图╮
    2020-12-13 21:46

    My solution in Swift:

    class MyTableViewController: UITableViewController {
    
    var sectionHeaderView:UIView?
    

    ...

    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
        sectionHeaderView = UIView(frame: CGRectMake(0, 0, self.tableView.frame.size.width, 30))
        sectionHeaderView?.backgroundColor = UIColor.grayColor()
    
        var button = UIButton(frame: CGRectMake(0, 0, self.tableView.frame.size.width, 30))
        button.backgroundColor = UIColor.darkGrayColor()
        button.setTitle("collapse/expand", forState: .Normal)
        button.addTarget(self, action: "collapseOrExpandSectionHeader", forControlEvents: .TouchUpInside)
    
        sectionHeaderView?.addSubview(button)
    
        return sectionHeaderView
    }
    

    ...

    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    
        if let sectionHeader = sectionHeaderView {
            return view.frame.size.height
        } else {
            return 30.0
        }
    }
    

    ...

    func collapseOrExpandSectionHeader() {
    
        if let sectionHeader = sectionHeaderView {
    
            let headerHeight:CGFloat
    
            if sectionHeader.frame.size.height == 200 {
                headerHeight = 30.0
            } else {
                headerHeight = 200.0
            }
    
            UIView.animateWithDuration(0.3, animations: {
                self.tableView?.beginUpdates()
                sectionHeader.frame.size.height = headerHeight
                self.tableView?.endUpdates()
            } )
        }
    }
    

提交回复
热议问题