如何解决如何根据SwiftUI中其他视图的按钮单击来更新视图
我经常遇到这种情况,但到目前为止我找不到一个好的解决方案。问题是,当我的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")
}
}
}
}
解决方法
以下是解决此类情况的可能方法的演示-职责分立,委派活动。
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()
// }
// }
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。