Search code examples
iosswiftdebuggingviewdidload

Swift 4 - The background function isn't working


I made this simple game with Swift 4 but it's not working.

Code :

class ViewController: UIViewController {
    @IBOutlet weak var TheCharacter: UIImageView!
    @IBOutlet weak var rocket1: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.rocket1.isHidden = true

        if 1 % 1 == 0 {
            if 0 == 0{
                self.rocket1.isHidden = false
                let xPosR = rocket1.frame.origin.x + 500
                let yPosR = rocket1.frame.origin.y

                let heightCharacterR = rocket1.frame.size.height
                let widthCharacterR = rocket1.frame.size.width

                UIView.animate(withDuration: 1.75, animations: {
                    self.rocket1.frame = CGRect(x: xPosR, y: yPosR
                        , width: widthCharacterR, height: heightCharacterR)
                }) { (finished) in

                }
                self.rocket1.isHidden = true
                self.rocket1.frame = CGRect(x: xPosR - 500, y: yPosR, width: widthCharacterR, height: heightCharacterR)
            }
        }
    }
}

I know it's being written badly but the problem is one of the rockets has to move in my screen (from one side to the other) because the condition is always true since 0==0 and 1 % 1 == 0. But it's not moving.

Why?


Solution

  • You are animating the views in viewDidLoad(), that is, before they are visible in the window. Move that code to viewDidAppear(). Then your views are visible and can be animated.

    And be sure your views are not using autolayout that constraint the frame. Animating the frame is not a good idea OTOH.