SwiftUI dismiss modal

前端 未结 13 2181
闹比i
闹比i 2020-11-29 23:23

Since SwiftUI is declarative there is no dismiss methode. How can is add a dismiss/close button to the DetailView?



        
13条回答
  •  庸人自扰
    2020-11-30 00:09

    The modal views in SwiftUI seem to be simple until you start using them in a List or Form views. I have created a small library which wraps all the edge cases and makes the using of modal views the same as NavigationView-NavigationLink pair.

    The library is open-sourced here: https://github.com/diniska/modal-view. You can include it into the project using Swift Package Manager, or just by copying the single file that the library includes.

    The solution for your code would be:

    struct DetailView: View {
        var dismiss: () -> ()
        var body: some View {
            Text("Detail")
            Button(action: dismiss) {
                Text("Click to dismiss")
            }
        }
    }
    
    struct ContentView : View {
        var body: some View {
            ModalPresenter {
                ModalLink(destination: DetailView.init(dismiss:)) {
                    Text("Click to show")
                }
            }
        }
    }
    

    Additionally, there is an article with full description and examples: How to present modal view in SwiftUI

提交回复
热议问题