user3992901
user3992901

Reputation:

Creating a random image generator with Swift

I'm trying to make a random image appear on the screen, but I'm new to Swift and am not sure how to do this. I have three images which I want have randomly shown in the image view, when the app is opened. How do I do this?

Upvotes: 2

Views: 10594

Answers (4)

nomnom
nomnom

Reputation: 994

It works for me (Swift 4.2):

let images: [UIImage] = [ #imageLiteral(resourceName: "randomImage1"),
                          #imageLiteral(resourceName: "randomImage2"), 
                          #imageLiteral(resourceName: "randomImage3")]
let randomImage = images.shuffled().randomElement()

Upvotes: 0

iOS_with_me
iOS_with_me

Reputation: 1

   imageArr = ["1.jpeg","2.jpeg","3.jpeg","4.jpeg"]
    let RandomNumber = Int(arc4random_uniform(UInt32(self.imageArr.count)))
    //imageArr is array of images
     let image = UIImage.init(named: "\(imageArr[RandomNumber])")

    let imageView = UIImageView.init(image: image)

Upvotes: 0

Bigfoot11
Bigfoot11

Reputation: 921

If the images are named basically the same thing. For example, "Image1.png, Image2.png, and Image3.png, then you can use this code:

override func viewDidLoad() {
    super.viewDidLoad()

  ImageView.image = UIImage(named: "Image\(arc4random_uniform(3) + 1).png")

  }

Upvotes: 2

codester
codester

Reputation: 37189

Generate a ramdom number from 0 to 2 and show the image by randomly generated number.

 var random = arc4random_uniform(3) //returns 0 to 2 randomly

  switch random {
    case 0:
        //show first image
    case 1:
        //show second image
    default:
        //show third image
  }

Upvotes: 6

Related Questions