How to generate random image using image view in swift

前端 未结 2 1815
日久生厌
日久生厌 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:51
    @IBAction func randomimage(sender: AnyObject)
    {
        //list of Images in array 
        let image : NSArray = [ UIImage(named: "1.jpg")!,
            UIImage(named: "2.jpg")!,
            UIImage(named: "3.jpg")!,
            UIImage(named: "4.jpg")!,
            UIImage(named: "5.jpg")!,
            UIImage(named: "6.jpg")!,
            UIImage(named: "7.jpg")!]
    
        //random image generating method
        let imagerange: UInt32 = UInt32(image.count)
        let randomimage = Int(arc4random_uniform(imagerange))
        let generatedimage: AnyObject = image.objectAtIndex(randomimage)
        self.myimage.image = generatedimage as? UIImage
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题