问题
in swiftui, I have a state variable count ,which is optional, in the sheet present ,I unwrap the optional and show Detailview, but it seems never hit there.
any idea how why not hit there?
it seems never hit
DetailView(count: num)
import SwiftUI
struct ContentView: View {
@State var showDetailView = false
@State var count : Int?
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 let num = self.count{
//never hit here
DetailView(count: num)
}
}
.navigationBarTitle("Your Reading")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DetailView: View {
var count: Int
var body: some View {
if count == 5 {
Text("5555")
} else {
EmptyView()
}
}
}
回答1:
The issue is not the optional unwrapping. The issue is that you are executing update to count while the body is being computed. To overcome this use my solution of: swiftui state variable count lost what it stored
Let me know if that solution does not work for you.
You could use this workaround (not recommended), if you really have to use @State var count.
DispatchQueue.main.async {
self.count = 5
}
回答2:
You can use sheet(item:content:)
instead of sheet(isPresented:content:)
:
struct ContentView: View {
@State var count: Int?
var testArr = [1, 2, 3, 4, 5]
var body: some View {
NavigationView {
List(testArr.indices) { index in
Text("row num \(index)")
.onTapGesture {
self.count = 5
}
}
.sheet(item: $count) { count in
DetailView(count: count)
}
.navigationBarTitle("Your Reading")
}
}
}
Note that item
must conform to Identifiable
, so you need to either use your own struct or create an Int
extension:
extension Int: Identifiable {
public var id: Int { self }
}
来源:https://stackoverflow.com/questions/64639269/how-to-deal-with-swiftui-state-optional-unwrap