Search code examples
swiftswiftuixcode11

Random Image when pressing a button in SwiftUI


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?


Solution

  • 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
    }