Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

swiftui state variable count lost what it stored

when I click onTapGesture event to setup

  self.showDetailView = true
  self.count = 5

the sheet will popup, but the self.count always be 0, not be 5. so the code Text("5555") will never be hitt.

it seems state variable count lost what it stored.

import SwiftUI

struct ContentView: View {
    @State var showDetailView = false
    @State var count = 0
    var testArr = [1,2,3,4,5]
    var body: some View {
        
        NavigationView {
            List(testArr.indices){ indice in
                Text("row num (indice)")
                    .onTapGesture{
                        
                        self.showDetailView = true
                        self.count = 5
                        }
                
                }
                .sheet(isPresented: self.$showDetailView) {
                    if self.count == 0{
                        //  print("count = 0")
                    }
                    if  self.count == 5{
                        Text("5555")
                    }
                
                }
            
                .navigationBarTitle("Your Reading")
        }
        }
    }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use @Binding to pass value to child view:

struct DetailView: View {
    @Binding var count: Int

    var body: some View {
        if count == 5 {
            Text("5555")
        } else {
            EmptyView()
        }

    }
}

in your .sheet:

.sheet(isPresented: self.$showDetailView) {
    if self.count == 0 {
        //  print("count = 0")
    }
    DetailView(count: $count)

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...