首页 > 解决方案 > 将参数传递给 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()
  }
}

标签: swiftswiftui

解决方案


你必须使用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)
        }
    }
}

推荐阅读