UIScrollview contentOffset changes when removed fr

2019-07-04 00:18发布

问题:

I have a weird bug concerning an UIScrollView. This view works fine, until the moment I remove it from the window (indirectly, it's a subview to a removed view).

I then perform some unrelated animation ; and when I put the views where they were, the scrollView's contentOffset has changed.

I put a breakpoint in setContentOffset: function, and got the following stack :

#0  -[TestScrollView setContentOffset:] (self=0x915fbd0, _cmd=0x7fb34cd, contentOffset={x = 80, y = -0}) at /Users/../TestScrollView.m:19
#1  0x008670ea in -[UIScrollView(Static) _adjustContentOffsetIfNecessary] ()
#2  0x0085db55 in -[UIScrollView(UIScrollViewInternal) _stopScrollingNotify:dealloc:pin:] ()
#3  0x0084e6ff in -[UIScrollView _didMoveFromWindow:toWindow:] ()
#4  0x008444bb in -[UIView(Internal) _didMoveFromWindow:toWindow:] ()
#5  0x008444bb in -[UIView(Internal) _didMoveFromWindow:toWindow:] ()
#6  0x008444bb in -[UIView(Internal) _didMoveFromWindow:toWindow:] ()
#7  0x008444bb in -[UIView(Internal) _didMoveFromWindow:toWindow:] ()
#8  0x00840c72 in -[UIView(Hierarchy) _postMovedFromSuperview:] ()
#9  0x0083f4c6 in __UIViewWasRemovedFromSuperview ()
#10 0x0083f141 in -[UIView(Hierarchy) removeFromSuperview] ()
#11 0x00166573 in __98+[App MyAnimationLaunchingMethod]_block_invoke_0 ...

I saw other questions when a scrollview changes its own contentOffset from a call to _adjustContentOffsetIfNecessary, for instance after a setFrame. However it doesn't seem to make any sense here, as its size doesn't change : it is just taken off from the screen (to be put on back later). So there's no reason for it to change its offset.

Is there some explanation to this ? Some way to prevent this change ?

I could block (or restore) manually the offset change, however I'm looking for a "clean" solution if available : it's a whole group of views which are removed from the window. Sometimes this particular scrollView is present in the views tree, usually not.. So the animation class should not know about the scrollview.

Any idea ?

Thanks in advance

回答1:

Kind of a hack, but you can put a test in your setContentOffset: and simply return if it has already been removed from its superview.