Using a loop for adding attributes to multiple UIImageViews

后端 未结 2 1726
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 06:11

I have 8 UImageViews that I am adding animations to. I know I can make the animation eight times, but can I use a loop -and maybe interpolation- for it?

He

2条回答
  •  走了就别回头了
    2021-01-28 06:49

    To create the animationImages, I would do this:

    dieImage0.animationImages = (0..<4).reduce([UIImage]()) { images, _ in
        return images + (1..<7).map { UIImage(named: "dicey-die\($0)")! }
    }
    

    It looks like animationImages consists of 24 UIImages - 4 sets of 6 images, where the name of the image is "dicey-dieN", (N is replaced by a number in the range (1..<7).)

    You can create a single array of six images like this:

    let images = (1..<7).map { UIImage(named: "dicey-die\($0)")! }
    

    You want to do that 4 times, and add all the arrays together. You do that with the call to (0..<4).reduce([UIImage]()) { ... }

    The result will be a single array with 24 images.

    Then, as @Chris Slowik suggested, create an array of dieImages and then loop through them to assign the random image:

    let dieImages = [dieImage0, dieImage1, dieImage2, dieImage3, dieImage4, dieImage5, dieImage6, dieImage7]
    
    for dieImage in dieImages {
        dieImage.image = randomImages.randomDice()
        dieImage.startAnimating()
    }
    

    Your entire motionEnded method should probably look something like this:

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        let dieImages = [dieImage0, dieImage1, dieImage2, dieImage3, dieImage4, dieImage5, dieImage6, dieImage7]
    
        for dieImage in dieImages {
            dieImage.image = randomImages.randomDice()
            dieImage.startAnimating()
        }
    
    }
    

    I think you were running into problems with dieImage0 because you were starting the animation before you assigned it a random image. Assign the image first, and then start animating.

提交回复
热议问题