将参数传递给 SwiftUI 表

mic*_*ica 1 swift swiftui

我需要将参数传递给calledFrom SwiftUI 中的工作表。
奇怪的是,该参数并未在第一次调用时使用,但它适用于以下调用。

import SwiftUI

struct ContentView: View {
    @State var showSheet = false
    @State var calledFrom = -1
    
    var body: some View {
        ForEach((1...4), id: \.self) { i in
            getButton(i)
        }
        .sheet(isPresented: $showSheet) { Dialog(calledFrom: calledFrom) }
        .padding()
    }
    
    func getButton(_ i : Int) -> some View {
        return Button("\(i)"){print("Button \(i) pressed"); calledFrom = i; showSheet = true }
    }
}

struct Dialog: View {
  var calledFrom : Int
  @Environment(\.presentationMode) private var presentationMode
  var body: some View {
    VStack{
      Text("Called from Button \(calledFrom)")
        Button("close"){presentationMode.wrappedValue.dismiss()}
    }
    .padding()
  }
}
Run Code Online (Sandbox Code Playgroud)

jn_*_*pdx 5

你必须使用sheet(item:)来获得你正在寻找的行为。在 iOS 14 中,sheet视图是在 @State 更改之前计算的:


struct ActiveItem : Identifiable {
    var calledFrom: Int
    var id: Int { return calledFrom }
}

struct ContentView: View {
    @State var activeItem : ActiveItem?
    
    var body: some View {
        ForEach((1...4), id: \.self) { i in
            getButton(i)
        }
        .sheet(item: $activeItem) { item in
            Dialog(calledFrom: item.calledFrom)
        }
        .padding()
    }
    
    func getButton(_ i : Int) -> some View {
        return Button("\(i)"){
            print("Button \(i) pressed");
            activeItem = ActiveItem(calledFrom: i)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)