【问题标题】:Swift: How to animate the rowHeight of a UITableView?Swift:如何为 UITableView 的 rowHeight 设置动画?
【发布时间】:2016-06-04 04:13:48
【问题描述】:

我正在尝试通过在 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!")
    })
}

结果:行高确实发生了变化,但没有出现任何动画。我不明白为什么动画不起作用。我是否应该在某个地方定义一些开始和结束状态?

【问题讨论】:

    标签: swift uitableview animation


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-10-27
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多