DevilAyan
DevilAyan

Reputation: 31

In SwiftUI, I have an object in view1 and a button in view2, I want to change the value of object on a button pressed from view 2. How I do this?

I am new to SwiftUI, I've designed the UI using swiftUI, and I have designed a reusable button in another view which I have called in view1. Now how can I make changes into view1 when I tap the button ?

This is my View 1:

struct ContentView: View {

@State var RandomNumber = 1

var body: some View {
    ZStack{
        Color(#colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1))
            .edgesIgnoringSafeArea(.all)
        
        VStack{
            Image("RollLogo")
            .background(
                Color.clear
                .blur(radius: 4.0)
                .offset(x: -2, y: -2)
            )
            .shadow(color: Color(#colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)), radius: 20.0, x: 10.0, y: 10.0)
            .shadow(color: Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)), radius: 20.0, x: -10.0, y: -10.0)
            
            Spacer()
            HStack {
                DiceImage(n: RandomNumber)
                //DiceImage(n: 1)
            }.padding(.horizontal)
            Spacer()
            
            Buttons(CustomColor: Color("Accent"))
            .padding(.top)
            Spacer()
            
        }
    }
  }
}

In view2 I have a rectangular view with gesture enabled. Now when I tap on it, am generating a random number, Now this random number I want to assign in view1 state variable.

.onTapGesture {
                let numberr = Int.random(in: 1...6)
                print("Am tapped",numberr)
        }

Upvotes: 1

Views: 50

Answers (1)

Asperi
Asperi

Reputation: 258541

You should pass RandomNumber by binding

HStack {
    DiceImage(n: $RandomNumber)    // << here !!
}.padding(.horizontal)

and in DiceImage

struct DiceImage: View {
   @Binding n: Int

   ...

   .onTapGesture {
                let numberr = Int.random(in: 1...6)
                print("Am tapped",numberr)
                self.n = numbers               // << here !!
        }
   ...
}

Upvotes: 1

Related Questions