swiftuitableviewhorizontal-scrollingcontentoffset

UITableView scrolling on reloaddata


I have UITableview in my project. I am getting new data when clicking add new button on footer. here is my app(demonstrated) https://pastenow.ru/e327ad5e4978777b280552c4e92f032d

When clicking on Add New Btn there is some little scrolling to up. i want to disable it and need to not scrolling uitableview to any direction. here is screenshot (demonstrated) https://pastenow.ru/e489ca3b9b5f78c31ad388cf8b3d02b9

i have checked setcontentoffset of uitableview, but it not works i dont know why.

override func viewDidLoad() {
        super.viewDidLoad()
        for i in 0...10 {
            items.append(i)
        }
    }

    @IBAction func addNewBtnClicked(_ sender: Any) {
        for i in 10...20 {
            items.append(i)
        }
        tableView.reloadData()    
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell") as! MyCell
        cell.titleLabel.text = "\(items[indexPath.row])"
        return cell
    }

Solution

  • I have also searched about this problem and until now I have not found a not hardcoded solution, but at least came to the following solution that works fine for my needs (it is almost the same as yours):

    extension UITableView {
    
        func reloadDataWithoutAnimation(scrollingAt desiredIndexPath: IndexPath, at desiredScrollPosition: UITableView.ScrollPosition) {
            UIView.performWithoutAnimation {
                reloadData()
                scrollToRow(at: desiredIndexPath, at: desiredScrollPosition, animated: false)
            }
        }
    
    }
    

    Usage:

    let indexPath = IndexPath(row: desiredRow, section: desiredSection)
    tableView.reloadDataWithoutAnimation(scrollingAt: indexPath, at: desiredScrollPosition)
    

    I hope it helps.