I'm developing an application using Storyboard with Xcode 12.3 and I need to animate the scrolling of a scrollView right after the view loads up on the screen and also when the user returns from another view controller to this view. It seems to me that the animation does not work if I scroll the view from within the viewDidLoad() function or from the function called when unwinding a segue. Instead, the view appears on the screen (in both cases) with the scrollview already scrolled at the respective location. Essentially, the end result is achieved but the scrolling animation is seemingly ignored or not executed.
Could anyone please help with this problem?
Here's my simple code that demonstrates the issue in both instances:
override func viewDidLoad {
super.viewDidLoad()
// ...
scrollView.setContentOffset(CGPoint(x: xOffset, y: yOffset), animated: true)
}
@IBAction func myUnwindAction(unwindSegue: UIStoryboardSegue) {
let segue = unwindSegue.source as! AnotherViewController
// ...
scrollView.setContentOffset(CGPoint(x: xOffset, y: yOffset), animated: true)
}
However, if I place the scrolling code in the IBAction of a test button and I click on this button after the view loads up, the view animates the scrolling smoothly and without any issues - Here's the code for this function:
@IBAction func testButton(_ sender: Any) {
scrollView.setContentOffset(CGPoint(x: xOffset, y: yOffset), animated: true)
}
Many thanks.
You need to use in viewDidAppear
you should google "View Controller Life Cycle"
var isFirst = true
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if isFirst {
isFirst = false
scrollView.setContentOffset(CGPoint(x: xOffset, y: yOffset), animated: true)
}
}