我经常遇到这种情况,但到目前为止我找不到一个好的解决方案。问题是,当我的SwiftUI视图变大时,我通过创建另一个结构并在相应的视图中调用该结构来重构代码。假设我有一个结构A,并在结构B中重构了一些代码,但是如何根据结构B上的按钮单击来更新视图或在结构A中调用函数?以下代码可能有助于了解这种情况:
import SwiftUI
struct ContentView: View {
@State var myText: String = "Hello World"
@State var isActive: Bool = false
var body: some View {
VStack {
Text(self.myText)
AnotherStruct(isActive: $isActive)
}
.onAppear {
if self.isActive == true {
self.getApi()
}
}
}
func getApi() {
print("getApi called")
self.myText = "Hello Universe"
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct AnotherStruct: View {
@Binding var isActive: Bool
var body: some View {
VStack {
Button( action: {
self.isActive.toggle()
}) {
Text("Button Tapped")
}
}
}
}
答案 0 :(得分:1)
以下是解决此类情况的可能方法的演示-职责分立,委派活动。
struct ContentView: View {
@State var myText: String = "Hello World"
var body: some View {
VStack {
Text(self.myText)
AnotherStruct(onActivate: getApi)
}
}
func getApi() {
print("getApi called")
self.myText = "Hello Universe"
}
}
struct AnotherStruct: View {
let onActivate: () -> ()
// @AppStorage("isActive") var isActive // << possible store in defaults
var body: some View {
VStack {
Button( action: {
// self.isActive = true
self.onActivate()
}) {
Text("Button Tapped")
}
}
// .onAppear {
// if isActive {
// self.onActivate()
// }
// }
}
}