动画折叠和展开表视图单元格

时间:2017-05-07 05:23:43

标签: ios swift animation swift3 tableview

我有一个带有可扩展单元格的UITableView,当你单击一个单元格时 - 它会扩展,其他打开的单元格会同时折叠动画。

这是我的代码:

的UITableViewDelegate

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  let cellToCollapse = getExpandedCell()
  if let cellToExpand = tableView.cellForRow(at: indexPath) as? MyTableViewCell {

    // Make animation for collapse and expand happen together
    DispatchQueue.global(qos: .userInitiated).async {
      cellToExpand.expand()
    }

    DispatchQueue.main.async {
      cellToCollapse?.collapse()
    }

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
      // This reloads cells' height
      tableView?.beginUpdates()
      tableView?.endUpdates()
    }
  }
}

MyTableViewCell

func expand() {
  UIView.animate(withDuration: 0.2,
    animations: { [weak self] () -> Void in
    if let frame = self?.collapsibleView.frame {
      self?.collapsibleView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: frame.height)
        }
      },
    completion: { _ in
      self.contentView.setNeedsLayout()
    })
}

func collapse() {
  UIView.animate(withDuration: 0.2,
    animations: { [weak self] () -> Void in
    if let frame = self?.collapsibleView.frame {
      self?.collapsibleView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: 0)
      }
    },
    completion: { _ in
      self.collapsibleView.removeFromSuperview()
      self.contentView.setNeedsLayout()
    })
}

此代码效果很好。

我的问题是 - 在这种情况下使用asyncAfter是否正确? 我更喜欢在这里使用完成块,但是,我不想将tableView传递给MyTableViewCell

0 个答案:

没有答案
相关问题