user1620383
user1620383

Reputation: 75

Automatically scroll to a subview in a scrollview

I have implemented a scrollview that has dynamic content: multiple sub-views displaying photos of players with player names under. The flow is: 1. On the main window, a player is selected. 2. User launches another view to add a new player. 3. When the user goes back to the main menu, the scroll view is refreshed completely so that the new player photo and name is also displayed.

At this time, the scroll-view should still have the previously selected player in focus but instead it is showing it from the beginning. So the question is: is there a method to automatically scroll to a specific position in the scrollview so the screen still has the selected player in focus?

Upvotes: 0

Views: 2073

Answers (2)

Mick MacCallum
Mick MacCallum

Reputation: 130193

Simple, create a CGPoint and a BOOL that you can retain after the view change and set them when you initially navigate away from that page. Then in viewDidAppear you can check if the BOOL is YES and use:

[myScrollView setContentOffset:myCGPoint animated:YES];

Or, if you want the scroll view to appear already scrolled to the correct position, do the same thing except in viewWillAppear with the animated flag set to NO.

Upvotes: 1

Anton
Anton

Reputation: 4018

Yes, there are two:

(1) scrollRectToVisible:animated:
(2) setContentOffset:animated:

You can read about both methods at UIScrollView Class Reference. Either way, you can use an instance variable to store the content offset or the visible rect when the user scrolls, and then use one of the methods I listed above to restore the scroll view position when the player data is updated.

Depending on what you are doing, you may find UITableView easier to implement because it is very customizable "out-of-the-box" and it has plenty of methods to help manage a list (including the ones I mentioned above, and more). If you're interested, have a look at UITableView Class Reference.

Upvotes: 1

Related Questions