Home > Back-end >  Add a button to refresh a element in a list
Add a button to refresh a element in a list

Time:12-26

I have a list of questions and when the app is launched one randomly pops up. Now I want when a button is clicked it shows another random question in the list. Any ideas?

This is my view

import SwiftUI

struct ViewJouer2: View {
    @EnvironmentObject var data : DefisList
    var body: some View {
        List {
            if let randomDefi = data.defis.randomElement() {
                DefiRow(Defi: randomDefi)
            }
        }
    }
}
struct ViewJouer2_Previews: PreviewProvider {
    static var previews: some View {
        ViewJouer2()
            .environmentObject(DefisList())
    }
}

This is my Data

import SwiftUI

class DefisList : ObservableObject {
    @Published var defis = [
        Defi(question: "How old are you?"),
        Defi(question: "How are you"),
        Defi(question: "What is your name?"),
    ]
}
struct Defi : Identifiable {
    var question : String
    
    var id = UUID()
}

CodePudding user response:

Make randomDefi a @Published variable of your ObservedObject. Add a method called randomize() to choose a random one and call that from your button.

import SwiftUI

struct ViewJouer2: View {
    @EnvironmentObject var data : DefisList
    var body: some View {
        List {
            DefiRow(defi: data.randomDefi)
        }
        Button("random") {
            data.randomize()
        }
    }
}

class DefisList : ObservableObject {
    @Published var randomDefi = Defi(question: "")
    
    private var defis = [
        Defi(question: "How old are you?"),
        Defi(question: "How are you?"),
        Defi(question: "What is your name?"),
    ]
    
    init() {
        randomize()
    }
    
    func randomize() {
        randomDefi = defis.randomElement()!
    }
}

struct Defi : Identifiable {
    var question : String
    
    var id = UUID()
}

struct DefiRow: View {
    let defi: Defi
    
    var body: some View {
        Text(defi.question)
    }
}
  • Related