ios – How to use index from table view row to determine page number


I have a table view that I am using to show chat channels inside my app.

How would I get the current page at the current visible index? I posted my code below.

    let currentVisibleIndex = indexPath.row
    let currentChannel = channelsViewModel[currentVisibleIndex]
        
        var totalPageCount: Int {
            let page = ceil(Double(channelsViewModel.count / ChatChannelsManager.channelsLimit))
            return max(1, Int(page))
        }

        var currentPageFirstIndex: Int {
            let index = totalPageCount == 1 ? 0 : (totalPageCount - 1) * ChatChannelsManager.channelsLimit
            return index
        }
        
        var currentPageLastIndex: Int {
            let index = (totalPageCount * ChatChannelsManager.channelsLimit) - 1
            return index
        }

This is the incorrect code:

       var visiblePage: Int {
            let index = currentVisibleIndex == 0 ? 1 : currentVisibleIndex
            let page = ceil(Double(index / channelsViewModel.count))
            return max(1, Int(page))
        }

       var visiblePageFirstIndex: Int {
            let index = visiblePage == 1 ? 0 : (visiblePage - 1) * ChatChannelsManager.channelsLimit
            return index
        }
        
        var visiblePageLastIndex: Int {
            let index = (visiblePage * ChatChannelsManager.channelsLimit) - 1
            return index
        }

These are some of the cases I’m trying to solve for, assuming each page has a limit of 15

Case 1:

  • total pages 1
  • start at channel index 0
  • end at channel index 14
  • current visible index 4
  • current visible page 1

Case 2:

  • total pages 2
  • start at channel index 15
  • end at channel index 29
  • current visible index 18
  • current visible page 2

Case 3:

  • total pages 4
  • start at channel index 45
  • end at channel index 59
  • current visible index 44
  • current visible page 3

Case 4:

  • total pages 4
  • start at channel index 45
  • end at channel index 59
  • current visible index 0
  • current visible page 1

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img