当咱们在工作中,总会遇到弹出多个Sheet的状况。弹出一两个的状况下,咱们能够运用绑定Boolean变量来完结。但是如果有很多种状况,会弹出很多种不同的Sheet咱们该怎么了来做呢?这便是咱们今天要解决的问题

绑定 Bool 值的办法

.sheet(isPresented: <#T##Binding<Bool>#>, content: <#T##() -> View#>)

这种办法当咱们有多个sheet要弹出时,就很麻烦。所以咱们建议运用下面办法来完结sheet的弹出,它具有更好的扩展性。

绑定Item办法

.sheet(
item: <#T##Binding<Identifiable?>#>, 
content: <#T##(Identifiable) -> View#>)

它需求一个完成了 Identifiable 协议的 Binding 值。

咱们用一个 Model 来承载显现的内容,让model完成 Identifiable 协议。

model 如下:

struct ItemModel: Identifiable {
    let id = UUID().uuidString
    let title: String
}

在运用sheet的地方写上如下代码:

.sheet(item: $selectItemModel) { itemModel in
  NextScreenView(itemModel: itemModel)
}

当你点击某个控件时,咱们需求改变 selectItemModel 的值。

Button("BUTTON (index)") {
  selectItemModel = ItemModel(title: "(index)")
}

这样便是能够完成多个sheet弹出的作用。


以下是全部代码

// multiple sheets
struct ItemModel: Identifiable {
    let id = UUID().uuidString
    let title: String
}
struct MultipleSheetsSample: View {
    @State var selectItemModel: ItemModel? = nil
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                ForEach(0..<20) { index in
                    Button("BUTTON (index)") {
                        selectItemModel = ItemModel(title: "(index)")
                    }
                }
            }
            .sheet(item: $selectItemModel) { itemModel in
                NextScreenView(itemModel: itemModel)
            }
        }
    }
}
struct NextScreenView: View {
    let itemModel: ItemModel
    var body: some View {
        Text(itemModel.title)
            .font(.largeTitle)
    }
}

大家有什么观点呢?欢迎留言讨论。

大众号:RobotPBQ

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。