How to generate random image using image view in swift

前端 未结 2 1814
日久生厌
日久生厌 2021-01-28 08:37

I just followed treehouse course and create my first Fun Fact app.In that they generate a random array quotes.

Needed:

I have placed image view

2条回答
  •  深忆病人
    2021-01-28 08:52

    The solution mainly is to use the same approach you have done with the random text. So to sum up, you should have an array of the images, and a function to select a random image. Then call that function from your view controller. A possible implementation to this approach is:

    Add this array to your FactBook

    let factsImagesArray = [
        "image1.png",
            "image2.png",
             "image3.png",
             "image4.png",
             "image5.png",
        ]
    

    Add this method to your FactBook

    func randomFactImage() -> UIImage {
        let unsignedArrayCount = UInt32(factsImageArray.count)
        let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
        let randomNumber = Int(unsignedRandomNumber)
        return UIImage(named: factsImageArray[randomNumber])!
    }
    

    and in your viewcontroller change showFunFact to:

    @IBAction func showFunFact() {
            let randomColor = colorWheel.randomColor()
            view.backgroundColor = randomColor
            funFactButton.tintColor = randomColor
            funFactLabel.text = factBook.randomFact()
    
            imgV.image = faceBook.randomFactImage()
        }
    

    Ofc you should have the image1.png, image2.png ... in your resources

提交回复
热议问题