Creating a random image generator with Swift

佐手、 提交于 2021-02-19 05:25:31

问题


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?


回答1:


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
  }



回答2:


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")

  }



回答3:


   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)



回答4:


It works for me (Swift 4.2):

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


来源:https://stackoverflow.com/questions/26569698/creating-a-random-image-generator-with-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!