Captain Code
Captain Code

Reputation: 277

How to create a random image generator from an array of images using a image view?

I want to generate a random background image from a UIImage array so every time the view loads a new background image is randomly selected from the elements of the array. I currently have the background image connect to an IBoutlet UIImageView. I've tried using arc4random but it gives me an error when I try to randomize the elements of the UIImage array by saying I cannot attach a int subscript to a UIImage. Any suggestions how to about this?

Here is part of the code:

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = [Mightymouse.png, Roadrunner.png, Mickeymouse.png, Donalduck.png, Sonic.png, Mario.png, Bugsbunny.png]

Upvotes: 0

Views: 1405

Answers (2)

Alwin Vazhappilly
Alwin Vazhappilly

Reputation: 1514

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = ["Mightymouse", "Roadrunner", "Mickeymouse", "Donalduck", "Sonic", "Mario", "Bugsbunny"]

func randomImgPicker() {
        let randomNumber = arc4random_uniform(UInt32(backgroundImages.count)) // generating random number
        backgroundImage.image = UIImage(named: backgroundImages[randomNumber])
    }

Upvotes: 2

Yedidya Reiss
Yedidya Reiss

Reputation: 5326

Can you add your code? From your description it seems that you are using arc4random on an UIImage, and not on array of UIImage...

Upvotes: 0

Related Questions