我目前正在使用SwiftUI开发应用程序。
此应用程序具有3种结构
这3种结构在“标签视图”中进行页面转换。
此应用使用ObservableObject批注具有Bool的常见变量类型。
我想更改FirstView和TextView在TextView中的显示和消失取决于变量的条件,但是FirstView不会像我期望的那样更改视图...
我该如何解决这种情况?
以下是代码:
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
FirstView()
.tabItem {
Text("First")
}.tag(1)
SecondView()
.tabItem {
Text("Second")
}.tag(2)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
FirstView.swift
import SwiftUI
struct FirstView: View {
@ObservedObject var firstCheck: ViewModel = ViewModel()
var body: some View {
VStack{
if firstCheck.check == true{
Text("checked")
}
}
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
SecondView.swift
import SwiftUI
struct SecondView: View {
@ObservedObject var secondCheck = ViewModel()
var body: some View {
VStack{
Toggle(
isOn: $secondCheck.check
){
Text("change")
}
if self.secondCheck.check == true{
Text("checked")
}
}
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
ViewModel.swift
import Foundation
final class ViewModel: ObservableObject {
@Published var check: Bool = false
}
Xcode:版本11.7
答案 0 :(得分:1)
将对象保留在一个地方,可以是父视图
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
// @StateObject var viewModel = ViewModel() // SwiftUI 2.0
var body: some View {
TabView {
// .. other code here
}
.environmentObject(viewModel) // << inject here
}
}
,然后在两个视图中使用(相同的第二秒)
struct FirstView: View {
@EnvironmentObject var firstCheck: ViewModel // declare only
// will be injected by type
var body: some View {
VStack{
if firstCheck.check == true{
Text("checked")
}
}
}
}