简体   繁体   English

为 swiftui 中的多个视图重用代码/属性

[英]reuse code/properties for several views in swiftui

we have several SwiftUI screens that are presented as sheet.我们有几个 SwiftUI 屏幕以表格形式呈现。 all of then can be dismissed by clicking a button.所有这些都可以通过单击按钮来解除。

so basically all of them have these 2 in common:所以基本上他们都有这两个共同点:

@Environment(\.presentationMode) var presentationMode
func dismiss() {
    presentationMode.wrappedValue.dismiss()
}

how can i declare them only once and just reuse them only in specific views?我怎样才能只声明一次并且只在特定视图中重用它们? i cannot use inheritance since they are stucts, extensions cannot contain state (except using a holder struct) and would add these to all instances of the same view type.我不能使用 inheritance 因为它们是结构,扩展不能包含 state(使用支架结构除外)并将这些添加到相同视图类型的所有实例中。

The .presentationMode is available throughout current view hierarchy, so we can use this feature to wrap & manage dismiss in some modifier. .presentationMode在当前视图层次结构中可用,因此我们可以使用此功能在某些修饰符中包装和管理关闭。

Here is a demo of solution based on button style, so any button can be specified as dismissing and it will dismiss current presentation.这是一个基于按钮样式的解决方案演示,因此任何按钮都可以指定为关闭,它将关闭当前的演示文稿。

Prepared with Xcode 12.1 / iOS 14.1用 Xcode 12.1 / iOS 14.1 制备

在此处输入图像描述

struct TestReuseDismissed: View {
    @State private var isActive = false
    var body: some View {
        Button("Show Sheet") {
            isActive = true
        }
        .sheet(isPresented: $isActive) {
            Button("Dismiss", action: { 
                   // do something before dismiss here !!
                })
                .buttonStyle(DismissButtonStyle())
        }
    }
}

struct DismissButtonStyle: PrimitiveButtonStyle {
    @Environment(\.presentationMode) var presentationMode

    func makeBody(configuration: Configuration) -> some View {
        Button(action: {
            configuration.trigger()
            dismiss()
        }) { configuration.label }
    }

    func dismiss() {
        presentationMode.wrappedValue.dismiss()
    }
}

backup 备份

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

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