Search code examples
swiftuitableviewtableviewscrollview

Swift tableView scroll to row gives a wrong value for the content Offset value of my tableview


In my application I have a tableview in which I am showing approximately 400 products. The problem I am facing is that while scrolling to the beginning of a section programmatically like so:

@objc func CategoryPress(_ button: UIButton) {

    let indexPath = NSIndexPath(item: 0, section: button.tag)
    tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.top, animated: false)

}

I am getting a wrong value for my tableView.contentOffset.y that stays incorrect until I reach the top of my tableview again. This issue happens only when scrolling to a position far from my start position.

While scrolling manually I am not facing this issue and all my values are exact.

I tried to scroll to a specific y on the button press but I didn't find a way to do this.

Any Solution or alternative to get the specific position would be highly appreciated.


Solution

  • I found a working alternative which is:

        @obj func CategoryPress(_ button: UIButton) {
    
        let indexPath = NSIndexPath(item: 0, section: button.tag)
        var offset: CGPoint = tableView.contentOffset
        offset.y = CGFloat(Ycoordinates[indexPath.section])
        tableView.setContentOffset(offset, animated: true)
    
    }