SwiftUI] Displaying Modal View in SwiftUI (Modal View)
Today, we will see how to launch Modal View in SwiftUI.
How to do the following in SwiftUI to bring up a modal view with existing Objective-C?
- (IBAction)showMyModal
{
MyModal *myModal = [[MyModal alloc]initWithNibName:@"MyModal" bundle:nil];
[myModal setModalTransitionStyle:UIModalTransitionStylePartialCurl];
[self presentModalViewController:myModal animated:YES];
}
First, create a SwiftUI project as an example and add a Button to the ContentView.
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
Text("Hello, World!")
Button(action: {
print("hello button!!")
}) {
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Define the view to be used as the next modal view.
struct ModalView: View {
var body: some View {
VStack {
Text("Modal view")
Button(action: {
}) {
Text("Dismiss")
}
}
}
}
As shown below, add .sheet modifier to the button of ContentView and define the variable showModal to save the state.
import SwiftUI
struct ContentView: View {
@State private var showModal = false //상태
var body: some View {
VStack{
Text("Hello, World!")
Button(action: {
print("hello button!!")
self.showModal = true
}){
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
}
.sheet(isPresented: self.$showModal) {
ModalView()
}
}
}
}
Print ModalView as the content of sheet.
When executed in this state, a modal view is displayed when the button is clicked as shown below.
However, there is no way to close the modal view.
Add an action to close the modal view to the Dismiss button of the modal view as shown below.
struct ModalView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
Group {
Text("Modal view")
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Dismiss")
}
}
}
}
Add an Environment variable and call dismiss on the button's action.
This is the final completion screen.
** Full source
//
// ContentView.swift
// SwiftUI_Modal
//
import SwiftUI
struct ContentView: View {
@State private var showModal = false
var body: some View {
VStack{
Text("Hello, World!")
Button(action: {
print("hello button!!")
self.showModal = true
}){
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
}
.sheet(isPresented: self.$showModal) {
ModalView()
}
}
}
}
struct ModalView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
Group {
Text("Modal view")
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Dismiss")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Comments
Post a Comment