Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does UITableView contentOffset change when using segmented control?

I have a UITableView which has a segmented control in its navigation bar. I am using the same table view to show 3 different sets of data, based on the selected index of the segmented control. I am now trying to preserve the scroll position for each segment option, so that it appears that there is one table for each segment option (i.e. the results of each selection have independent scroll positions).

To do this, I am storing one CGPoint variable for each state, which is set to the contentOffset when the selected segment index changes. The variable is used to set the table view's content offset upon segment change.

However, it seems like the contentOffset value changes when the selected segment index changes without any visible change to the position within the table. It is like the 0-position of the content offset is moving, which makes my stored values now wrong.

When my controller contains the following methods:

override func viewDidLoad() {
    // set up the view here...        

    print(tableView.contentOffset)
}

@IBAction func selectedSegmentChanged(sender: AnyObject) {
    print(tableView.contentOffset)

    // code to change the data shown in the table view...
}

I get the following logged when the view loads:

(0.0, 0.0)

but after changing the segment I get:

(0.0, -64.0)

All states show the table view scrolled to the exact same position, that is - at the top.

This behaviour is preventing me from being able to store the scroll position properly, as the 'meaning' of the content offset seems to be changing.


Edit: the content offset is in fact being adjusted between viewDidLoad() and viewDidAppear(), most likely due to a content inset. So I am now storing the content offset value the first time viewDidAppear() is called.

like image 244
Andrew Bennet Avatar asked Feb 07 '23 06:02

Andrew Bennet


2 Answers

This issue is usually caused by a property on the view controller. Setting it to false should fix it.

self.automaticallyAdjustsScrollViewInsets = false

It can also be set from the storyboard. Just select the view controller and uncheck Adjusts scroll view insets.

like image 59
Jelly Avatar answered Feb 13 '23 07:02

Jelly


Setting the tableview estimatedRowHeight fix the problem tableView.estimatedRowHeight = Cell_Row_Height

like image 40
Syed Zahid Shah Avatar answered Feb 13 '23 05:02

Syed Zahid Shah