user3847113 user3847113 - 20 days ago 6
iOS Question

UIScrollView doesn't scroll second time it's opened

I have UIViewController that have UIScrollView with lots of Labels and ImageViews inside and I set height of UIScrollView using:

override func viewDidLayoutSubviews() {
scrollView.contentSize = CGSize(width: self.contentView.frame.width, height:
self.labelTitle1.frame.height +
self.labelTitle2.frame.height +
self.labelTitle3.frame.height +
...
self.imageView1.frame.height +
self.imageView2.frame.height +
self.imageView3.frame.height +
...)
}


This works for the first time when I open that UIViewController, but if I go back using UINavigationController and then open again that UIViewController with the same post I'm not able to scroll down.

If I then open another post inside that UIViewController I'm able to scroll down but only for the first time it's opened.

Same thing is for all the posts, they scroll only the first time when they are opened.

Why is that happening and how to fix it?

Answer

Move your code to viewDidAppear() so that you end up with something looking like

override func viewDidAppear() {

    scrollView.contentSize = CGSize(width: self.contentView.frame.width, height:
        self.labelTitle1.frame.height +
        self.labelTitle2.frame.height +
        self.labelTitle3.frame.height +
        ...
        self.imageView1.frame.height +
        self.imageView2.frame.height +
        self.imageView3.frame.height +
        ...)
}