簡體   English   中英

SwiftUI 在預覽模式下用按鈕關閉模態

[英]SwiftUI close modal with a button in preview mode

我有一個簡單的 Button,當它被點擊時會打開一個 Modal。 我知道模式可以通過向下滑動來關閉,但我實現了一個按鈕來關閉它,這很有效。

唯一困擾我的是我無法預覽我的模態(看看我下面的代碼)


// Button that opens the modal
struct ContentView: View {
  @State private var willMoveToNextScreen = false
  Button(action: {
          self.willMoveToNextScreen = true
     }, label: {
           Image(systemName: "gear")
                 .font(.system(size: 30))
                 .padding(.leading, 15)
            })
            .sheet(isPresented: $willMoveToNextScreen, content: {
                    SettingsView(willMoveToNextScreen: $willMoveToNextScreen)
     })
}


// Modal
 struct SettingsView: View {
     @Binding var willMoveToNextScreen: Bool
    
      var body: some View {
        VStack{
            HStack {
                Button(action: {
                    self.willMoveToNextScreen = false
                }, label: {
                    Image(systemName: "xmark")
                        .font(.system(size: 30, weight: .semibold))
                })
            }
            .frame(maxWidth: .infinity, alignment: .trailing)
            .padding(15)
            Spacer()
            Text("Aye")
        }
    }
}

struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        // I don't know which value I should provide, it expects a Binding<Bool> value
        SettingsView(willMoveToNextScreen: ??) 
    }
}

willMoveToNextScreen需要一個 BindingBoolean。 我該如何解決這個問題?

使用Binding.constant(true) 您可以使用Binding.constant(/*Pass your default value as per type*/)PreviewProvider設置數據。

struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        SettingsView(willMoveToNextScreen: .constant(true)) // Pass true or false
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM