swiftui 状态变量计数丢失了它存储的内容 [英] swiftui state variable count lost what it stored
本文介绍了swiftui 状态变量计数丢失了它存储的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我点击 onTapGesture 事件进行设置时
when I click onTapGesture event to setup
self.showDetailView = true
self.count = 5
工作表会弹出,但self.count总是0
,而不是5
.所以代码 Text("5555")
永远不会被命中.
the sheet will popup, but the self.count always be 0
, not be
5
.
so the code Text("5555")
will never be hitt.
状态变量 count 似乎丢失了它存储的内容.
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()
}
}
推荐答案
另一种方法是:
class CountModel: ObservableObject {
@Published var count: Int = 0
init(_ c: Int) { self.count = c }
}
struct ContentView: View {
@State var showDetailView = false
@ObservedObject var model = CountModel(0)
var testArr = [1,2,3,4,5]
var body: some View {
NavigationView {
List(testArr.indices) { indice in
Text("row num \(indice)")
.onTapGesture {
self.model.count = 5
self.showDetailView = true
}
}
.sheet(isPresented: self.$showDetailView) {
if self.model.count == 0 {
let _ = print("count = 0")
Text("0000")
}
if self.model.count == 5 {
let _ = print("count = 5")
Text("5555")
}
}
.navigationBarTitle("Your Reading")
}
}
这篇关于swiftui 状态变量计数丢失了它存储的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文