How to generate random image using image view in swift

断了今生、忘了曾经 提交于 2019-12-02 08:17:16

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

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