简体   繁体   English

自动滚动到滚动视图中的子视图

[英]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. 流程为:1。在主窗口中,选择一个播放器。 2. User launches another view to add a new player. 2.用户启动另一个视图以添加新玩家。 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. 3.当用户返回主菜单时,滚动视图将完全刷新,以便还显示新的播放器照片和名称。

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? 所以问题是:是否有一种方法可以自动滚动到滚动视图中的特定位置,以便屏幕仍然具有所选择的播放器?

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. 简单,创建一个CGPointBOOL ,您可以在视图更改后保留它们,并在最初离开该页面时设置它们。 Then in viewDidAppear you can check if the BOOL is YES and use: 然后在viewDidAppear您可以检查BOOL是否为YES并使用:

[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 . 或者,如果您希望滚动视图显示已滚动到正确的位置,请执行相同的操作,但在viewWillAppear中将动画标记设置为NO

Yes, there are two: 是的,有两个:

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

You can read about both methods at UIScrollView Class Reference . 您可以在UIScrollView类参考中阅读这两种方法。 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). 根据您正在做的事情,您可能会发现UITableView更容易实现,因为它是非常可定制的“开箱即用”,它有很多方法可以帮助管理列表(包括我上面提到的那些,等等) 。 If you're interested, have a look at UITableView Class Reference . 如果您有兴趣,请查看UITableView Class Reference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM