Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 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 Reply

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)

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...