簡體   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