Search code examples
iosuiviewuiscrollviewlagaddsubview

Source of lag when adding/removing UIViews to UIScrollview?


Problem:

Adding/removing subviews to/from a UIScrollView causes noticeable lag.

Details:

I have a UIScrollView (with paging enabled) that will contain a couple dozen 'pages'. The content size of this UIScrollview is the number of pages * the width of the UIScrollView.

Each of these pages is a subview that I build from some file system access. My UIScrollView keeps three pages around as subviews: the current page, and its left/right neighbours. Loading/eviction of the neighbouring subviews takes place when the current page is half offscreen, which is when the disk access and manipulation of view hierarchy occurs.

When I first encountered this my immediate thought was that the disk access/building the subview is the source of the lag. I've since moved to this an NSTimer, and am still experiencing the same lag.

I'm starting to suspect that the lag is caused by addSubview (adding subview to UIScrollView) and removeFromSuperview (removing subviews from UIScrollView).

Subviews are added directly to UIScrollView. I don't have a 'content view' inside the UIScrollView that I add them to.

Question:

Is this a common problem/bottleneck? Is there a better pattern for loading of these pages?


Solution

  • The problem ended up being setting the image property of the subviews. UIImage does not perform its processing right away, only in preparation for appearing on screen -- this is what was causing the lag.

    The question lead me down the right track:

    Setting image property of UIImageView causes major lag

    Their solution was to decompress/process the image ourselves using Core Graphics, and it worked beautifully.