在SwiftUI中点击ActionSheet.Button后如何显示视图?

时间:2019-06-26 20:32:06

标签: ios swift swiftui

我一直在玩SwiftUI,并为这个简单的东西而感到困惑。基本上,我试图在点击ActionSheet.Button之后触发模式。到目前为止,这是我的代码:

struct SomePage: View {
    @State var showSheet = false

    var body: some View {
        Button(action: {
            self.showSheet = true
        }) { 
            Text("Show ation sheet") 
        }.presentation(sheet)
    }

    private var sheet: ActionSheet? {
        let button = ActionSheet.Button.default(Text("Button") {
             self.showSheet = false
             // what now??
        }
        let action = ActionSheet(title: Text("Title"),
                                 message: nil,
                                 buttons: [button])
        return showSheet ? action : nil
    }

    // This is the modal I'm trying to present 
    // after tapping on the action sheet button
    private var modal: Modal {
        return Modal(SomePage())
    }
}

我尝试在按钮上添加第二个presentation处理程序并切换showModal属性,但是显然调试器抱怨在第一个模式演示仍在演示时尝试第二种模式演示。

有人对如何进行这项工作有想法吗?

1 个答案:

答案 0 :(得分:2)

您离它并不远。

添加另一个@State来处理模态的表示。

struct ContentView: View {

    @State var showSheet = false
    @State var showModal = false

    var body: some View {
        Button(action: {
            self.showSheet = true
        }) {
            Text("Show action sheet")
        }
        .presentation(showSheet ? sheet : nil)
        .presentation(showModal ? modal : nil)
    }

    private var sheet: ActionSheet {
        let button = ActionSheet.Button.default(Text("Show modal")) {
            self.showSheet = false
            self.showModal = true
        }
        let actionSheet = ActionSheet(title: Text("Action Sheet"),
                                      message: nil,
                                      buttons: [button])
        return actionSheet
    }

    private var modal: Modal {
        return Modal(EmptyView()) {
            self.showModal = false
        }
    }
}

结果

enter image description here