繁体   English   中英

SwiftUI 在视图之间传递数据

[英]SwiftUI pass data from view to view

我今天花了 14 个小时试图弄清楚,我去了这里,用谷歌搜索,看视频,但没有任何帮助。 我放弃了,所以我决定问一个问题。

通常,我将两个视图合二为一,例如左侧的列表和右侧的详细信息。 在 iPhone 上,我可以使用工作表弹出第二个视图而没有任何问题,但在 iPad 上,我在右侧有第二个视图,当我单击列表时它不会更新。 我尝试了@Binging 和@State,但没有奏效。

如何将数据从一个视图传递到另一个视图?

导航链接代码:

let navigationItemList: [NavigationItems] = [NavigationItems(image: Image(systemName: "hourglass"), title: "Feature 1", subtitle: "Subtitle", linkView: AnyView(FeatureView1())),
                                             NavigationItems(image: Image(systemName: "clock.arrow.2.circlepath"), title: "Feature 2", subtitle: "Subtitle", linkView: AnyView(FeatureView2()))]
struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                Section(footer: MainFooterView()) {
                    ForEach(navigationItemList) { items in
                        HStack {
                            items.image?
                                .frame(width: 30, height: 30)
                                .font(.system(size: 25))
                                .foregroundColor(color3)
                            Text("")
                            NavigationLink(items.title, destination: items.linkView)
                        }
                        .listRowBackground(Color.clear)
                        .listRowSeparatorTint(.clear)
                        
                    }
                    .navigationTitle("Features")
                    .listStyle(.insetGrouped)
                }
            }
        }
    }
}

第一种观点:

struct FeatureView1 : View {
var body: some View {
   HStack {
      List(item) { items in
         Button("Click to update title in Feature View 2") {
            FeatureView2(title: "Button Called") //Nothing happened
         }
      }
      FeatureView2()
   }
}

第二种观点:

var body: some View {
   var title = ""
   ZStack {
      Text(title) //When I click a button from the list, it should show "Button Called", but nothing happens.
   }
}

在自动化之前,尝试做一个简单的例子来了解如何在视图之间共享数据:(如您所见,目标视图以标题作为参数)

 struct ContentView: View { var body: some View { NavigationView { NavigationLink(destination: FeatureView1(title: "FeatureView1")) { Text("Go to FeatureView1") } } } } struct FeatureView1: View { var title: String var body: some View { Text(title) NavigationLink(destination: FeatureView2(title: "FeatureView2")) { Text("Go to FeatureView2") } } } struct FeatureView2: View { var title: String var body: some View { Text(title) } }

根据您的用例,还有许多其他方法可以在视图之间共享数据,稍后我让您看到@EnvironmentObject、@Binding 等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM