Place UITableViewCell below siblings

I am trying to create a custom UITableView that acts similarly to a reminder app.

Instead of the topmost visible cell scrolling off the screen, I want it to be covered by the next cell so that the cells appear on top of each other as they scroll.

I am currently using:

override func scrollViewDidScroll(scrollView: UIScrollView) {

  let topIndexPath: NSIndexPath = tableView.indexPathsForVisibleRows()?.first as! NSIndexPath

  let topCell = tableView.cellForRowAtIndexPath(topIndexPath)

  let frame = topCell!.frame

  topCell!.frame = CGRectMake(frame.origin.x, scrollView.contentOffset.y, frame.size.width, frame.size.height)
}

      

But the top cell is always above the second cell, causing the second cell to scroll below it.

Also if I scroll quickly it seems to be misusing all my cells.

EDIT: Fix this. The answer will be posted below for future reference.

+3


source to share


1 answer


For anyone looking for this in the future. Just swipe over all visible cells and set their z position to their row number (so that each cell flows down over the previous one).

The if statement tells the top cell to stay on the contentOffset of the scroll and for all other cells to guess their expected position. This stops other cells from shifting if you scroll too fast.



override func scrollViewDidScroll(scrollView: UIScrollView) {

  // Grab visible index paths
  let indexPaths: Array = tableView.indexPathsForVisibleRows()!

  var i = 0
  for path in indexPaths {
    let cell = tableView.cellForRowAtIndexPath(path as! NSIndexPath)
    // set zPosition to row value (for stacking)
    cell?.layer.zPosition = CGFloat(path.row)

    // Check if top cell (first in indexPaths)
    if (i == 0) {
      let frame = cell!.frame

      // keep top cell at the contentOffset of the scrollview (top of screen)
      cell!.frame = CGRectMake(frame.origin.x,
                                scrollView.contentOffset.y,
                                frame.size.width,
                                frame.size.height)
    } else {
      // set cell frame to expected value
      cell!.frame = tableView.rectForRowAtIndexPath(path as! NSIndexPath)
    }
    i++
  }

}

      

0


source







All Articles