How can I make scrollview scroll to bottom a little bit and scroll to top a little bit again. I has to be animated so users will notice there is a scroll view. I tried this code block but didn’t work.
public extension UIScrollView {
func scrollToBottom(animated: Bool) {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
setContentOffset(bottomOffset, animated: animated)
}
func scrollToTop(animated: Bool) {
setContentOffset(.zero, animated: animated)
}
func scrollableAnimation(animated: Bool) {
scrollToBottom(animated: animated)
UIView.animate(withDuration: 0.5, delay: 0.5) {
self.scrollToTop(animated: animated)
}
}
}
2
Answers
You can play with this code and also change the animation accordingly . you can change the x and y value to change the scroll position accordingly
I have reason to believe that your call to get the
contentSize.height
of the scrollview content returns0
.Example I have used
I made a VC with a
UIScrollView
which embeds aUIStackView
, which in return has multipleUIViews
of various sizes embedded in it.Heights of each
UIViews
embedded in theUIStackView
are as follows (See the results gif for to better understand):Solution
To rectify the issue of content height being
0
, add a computed property that will get the contentSize after laying out any subviews in the scroll view. Refer toscrollViewContentHeight: CGFloat
in the following code:This will return the actual content height (in the case of my example,
2000
) of the scrollView. Using this, you can run the animations using the scroll view animations you have provided.It is important that you trigger the animations in the
viewDidAppear(animated:)
lifecycle function as that is where animations are usually triggered. And more importantly, that’s when the user will first see the view, meaning the content of the entire VC (including the scroll view) would have already been loaded.Results
Here I have added a
print()
statement inside theviewDidAppear(animated:)
function to verify the content height of the scroll view:Finally, the results of the experiment can be seen in the gif below, followed by the code: