Swift:如何动画化UITableView的rowHeight?

16

我尝试通过在tableView函数内调用startAnimation()来使tableViewCell行的高度动态变化:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TableViewCell

    tableView.rowHeight = 44.0

    startAnimation(tableView)

    return cell
}

//MARK: Animation function

func startAnimation(tableView: UITableView) {

    UIView.animateWithDuration(0.7, delay: 1.0, options: .CurveEaseOut, animations: {

        tableView.rowHeight = 88.0

    }, completion: { finished in

        print("Row heights changed!")
    })
}

结果:行高确实变了,但没有任何动画发生。我不明白为什么动画不起作用。也许我需要在某个地方定义一些起始和结束状态吗?

1个回答

29

不要用那种方式更改高度。相反,当您知道要更改单元格的高度时,请在任何函数中调用:

self.tableView.beginUpdates()
self.tableView.endUpdates()

这些调用会通知tableView检查高度变化。然后实现委托方法override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat并为每个单元格提供正确的高度。高度的变化将自动进行动画处理。对于那些没有显式指定高度的项目,您可以返回UITableViewAutomaticDimension

我不建议在cellForRowAtIndexPath中执行此类操作,而是在响应点击事件的方法(例如didSelectRowAtIndexPath)中执行。在我的一个类中,我这样做:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath == self.selectedIndexPath {
      self.selectedIndexPath = nil
    }else{
      self.selectedIndexPath = indexPath
    }
  }

internal var selectedIndexPath: NSIndexPath? {
    didSet{
      //(own internal logic removed)

      //these magical lines tell the tableview something's up, and it checks cell heights and animates changes
      self.tableView.beginUpdates()
      self.tableView.endUpdates()
    }
  }

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath == self.selectedIndexPath {
      let size = //your custom size
      return size
    }else{
      return UITableViewAutomaticDimension
    }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接