I'm trying to make a random image appear on the screen, when I am pressing a button. I have three images which I want to be randomly shown, when I press the button. How do I do this?
Asked
Active
Viewed 1,596 times
-2
-
Hi Jugap! Welcome to StackOverflow! This is a good question, but in the future, you should break it up into more specific parts with additional detail. For example, [this question](https://stackoverflow.com/questions/26569698/creating-a-random-image-generator-with-swift?rq=1) is a duplicate of yours but is also more specific. – Sam Spencer Jun 07 '20 at 17:29
1 Answers
3
If you are using an Array you can use the .randomElement(). Here's a simple example using the symbols from SF Symbols.
struct RandomImage: View {
@State var random: String = ""
var body: some View {
VStack {
Image(systemName: random)
Button(action: {
self.random = chooseRandomImage()
}) {
Text("Another one!")
}
}
}
}
var images = ["sun.max.fill", "moon.fill", "star.fill"]
func chooseRandomImage() -> String {
let array = images
let result = array.randomElement()!
return result
}

Wood
- 110
- 7