我正在创建一个动画序列,当按下一个按钮时,一个对象会淡出。再次按下同一按钮时,另一个对象消失。这种情况一直持续到淡出8个对象为止。我已经尝试并尝试了代码,到目前为止,代码已经使一个对象淡出,一次可以淡出两个或多个对象,但是如上所述却未能成功实现。到目前为止,这是我的代码:

import UIKit

class DrinkWaterViewController: UIViewController {

    @IBOutlet weak var glassOne: UIImageView!
    @IBOutlet weak var glassTwo: UIImageView!
    @IBOutlet weak var glassThree: UIImageView!
    @IBOutlet weak var glassFour: UIImageView!
    @IBOutlet weak var glassFive: UIImageView!
    @IBOutlet weak var glassSix: UIImageView!
    @IBOutlet weak var glassSeven: UIImageView!
    @IBOutlet weak var glassEight: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.glassOne.alpha = 1.0
        self.glassTwo.alpha = 1.0
    }

    @IBAction func drunkOne(_ sender: Any){

        if self.glassOne.alpha == 1.0{

        UIView.animate(withDuration: 1.5, delay: 0.2, animations:
            {self.glassOne.alpha = CGFloat(0.1)}
        )
    }
}

最佳答案

将眼镜放入数组glasses,并添加属性以跟踪nextToFade。然后只需淡化glasses[nextToFade]并将nextToFade递增1

class DrinkWaterViewController: UIViewController {

    @IBOutlet weak var glassOne: UIImageView!
    @IBOutlet weak var glassTwo: UIImageView!
    @IBOutlet weak var glassThree: UIImageView!
    @IBOutlet weak var glassFour: UIImageView!
    @IBOutlet weak var glassFive: UIImageView!
    @IBOutlet weak var glassSix: UIImageView!
    @IBOutlet weak var glassSeven: UIImageView!
    @IBOutlet weak var glassEight: UIImageView!

    // array to hold the glasses so that they can be indexed
    var glasses = [UIImageView]()

    // index of next glass to fade
    var nextToFade = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // put the glasses into the array
        glasses = [glassOne, glassTwo, glassThree, glassFour,
                    glassFive, glassSix, glassSeven, glassEight]

        // make sure they're all visible
        glasses.forEach { $0.alpha = 1.0 }
    }

    @IBAction func drunkOne(_ sender: Any) {
        // make sure not to index beyond the end of the array
        guard nextToFade < glasses.count else { return }

        let glass = glasses[nextToFade]
        nextToFade += 1
        UIView.animate(withDuration: 1.5, delay: 0.2, animations:
            { glass.alpha = 0.1 }
        )
    }
}

10-05 21:37