总的来说,我是 Swift 和 iOS 开发的新手。
我正在 SwiftUI 中构建一个应用程序。假设不同文件中有 2 个单独的视图:MainView() & Results() 和 TabBar()(忽略命名,这只是一个示例)(这 2 个视图位于 2 个单独的选项卡上)
我的目标是按下 ResultsView() 中的按钮并将 MainView() 的 textValue 属性更改为其他内容,然后在 MainView() 上显示更改。我怎样才能做到这一点? P.S 请忽略对齐等。我是 StackOverflow 的新手
struct MainView: View {
@State var textValue: String = "Old Text"
var body: some View {
Text(textValue)
}
}
struct TabBar: View {
var body: some View {
TabView {
MainView()
.tabItem {
Label("Main", systemImage: "circle.dashed.inset.filled")
}
ResultsView()
.tabItem {
Label("Results", systemImage: "person.2.crop.square.stack.fill")
}
}
}
}
struct ResultsView: View {
var body: some View {
Button {
// HOW TO UPDATE MainView.textValue?
} label: {
Text("Update")
}
}
}
- ContentView() 主体中只有 TabBar()
基本上,我的问题是我们如何从另一个视图更改某个视图的 UI?没有导航链接
可能听起来像是一个菜鸟问题,但任何回复将不胜感激!
您可以通过传递来实现这一点textValue
从 MainView 到 DetailView 通过@Binding
.
struct MainView: View {
@State private var text: String = "Original"
var body: some View {
NavigationView {
VStack {
Text(text)
NavigationLink("Detail", destination: DetailView(text: $text))
}
}
}
}
struct DetailView: View {
@Binding var text: String
var body: some View {
Button("Change Text") {
text = "New Text"
}
}
}
我建议你阅读本文 https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-binding-property-wrapper关于绑定,因为它解释了如何从其他地方更改视图。
Edit:因为你提到,这两种观点都在一个TabBar
,这里应该是一个工作示例:
struct ContentView: View {
@State private var text: String = "Original Text"
var body: some View {
TabView {
MainView(text: $text)
.tabItem { ... }
DetailView(text: $text)
.tabItem { ... }
}
}
}
struct MainView: View {
@Binding var text: String
var body: some View {
Text(text)
}
}
struct DetailView: View {
@Binding var text: String
var body: some View {
Button("Change Text") {
text = "New Text"
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)