How to prevent content from shifting when content grows

tl; dr I don't want to increase the dimensions UIViews

above the top of the content window UIScrollView's

to push the content below it down.

I have UIScrollView

one that displays a list of numbers UIStackViews

, and one of the advantages UIStackViews

is that when you set isHidden = false

to one of your subviews, it automatically resizes to compensate for the new view.

Now each list item has one of these UIStackViews

, and the user can click a button that sets isHidden = false

in the subview in each of them, all at once. This means that each list item will grow by an amount equal to the height of the unclosed view (same height for each stack view).

No problem if the scrollview contentOffset

is zero, because all height increases just push all other content down and the user will still be at the top of the scroll after all views are unhidden.

The problem is that the user is not at the top of the scroll. If so, and the user presses a button that displays all views, increasing the height will push all views downward, giving the view a scroll up. The further the user scrolls down the list, the more views are above him, and the more the content moves when the user clicks the button.

The behavior I'm looking for is the same as when the user clicks on the button, when it scrolls to the top of the view, but at any scroll position. In other words: no matter where the user scrolls when they click the button, the only views that are clicked are those below the top of the scroll content window.

Any idea how to do this?

+3


source to share


1 answer


Ok, let me see if I understand your question correctly.

This is the state of the scroll

 A
 B
 C
 D
 E

      

When the user clicks on the expand all button, it looks like this:

 A
 -1
 -2
 -3
 B
 -1
 +-a
 +-b
 -2
 C
 -1
 -2
 -3
 D
 -1
 -2
 E
 -1
 -2
 -3
 -4

      

The problem is that if the user is currently looking at

+---+
|D  |
|E  |
+---+

      



(which are the 4th and 5th items in the list) they end up looking at the expanded list:

+---+
|B  |
|-1 |
+---+

      

But they should be able to see the items D

they looked at earlier.

I would most likely recommend using UITableView

, as you can keep the currently visible TableViewCells and then when the view animation is active, highlight the current cell (which should support it relatively in the view).

In your case UIScrollView

, what I would recommend is grabbing the current visible subviews (using the current contentOffset

/ Size

and unit frames), then figuring out where they are after watching the animation resize it, and then scroll to the new position.

This, as I mentioned, is a more suitable task for UITableView

or UICollectionView

where parent objects are tracked and cached by the OS and there are certain rules governing row / cell insertion / deletion.

HtH

+2


source







All Articles