Search code examples
iosswiftxcodecalayeruibezierpath

Approach to load data / graphics / background before ViewController appears


I have an animated background on my view in my ViewController, calling it here:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    gradientSet.append([gradientOne, gradientTwo])
    gradientSet.append([gradientTwo, gradientThree])
    gradientSet.append([gradientThree, gradientOne])

    gradient.frame = self.view.bounds
    gradient.colors = gradientSet[currentGradient]
    gradient.startPoint = CGPoint(x:0, y:0)
    gradient.endPoint = CGPoint(x:1, y:1)
    gradient.drawsAsynchronously = true
    viewBackground.layer.addSublayer(gradient)

    animateGradient()
}

It depends on the loading time, but I see how I have "white flashes" when I load the ViewController via a button click. I have never seen this behavior on a professional App, so I think I am doing something fundamentally wrong.

How do I load colors, data, background stuff before the ViewController appears to have a seamless transition without white flashes between the loading time?


Solution

  • Add your code in viewWillAppear instead of viewDidAppear

    override func viewWillAppear(_ animated: Bool) {
        super. viewWillAppear(animated)
    
        gradientSet.append([gradientOne, gradientTwo])
        gradientSet.append([gradientTwo, gradientThree])
        gradientSet.append([gradientThree, gradientOne])
    
        gradient.frame = self.view.bounds
        gradient.colors = gradientSet[currentGradient]
        gradient.startPoint = CGPoint(x:0, y:0)
        gradient.endPoint = CGPoint(x:1, y:1)
        gradient.drawsAsynchronously = true
        viewBackground.layer.addSublayer(gradient)
    
        animateGradient()
    }