The modal view already has built-in support for the swipe down gesture, allowing users to naturally swipe down to close it. However, it is important to note that not all users are familiar with this gesture, especially those new to the iPhone. Therefore, it would be beneficial to provide an alternative way to close the modal view, such as a Close button. In the following image you can see an example of the button we are going to create, which is positioned in the top right corner:
We can make a dismiss modal view close using the dismiss environment variable. To achieve this we have to declare the variable:
@Environment(.dismiss) var dismiss
To create the close button we can attach the modifier overlay to the scroll view as follows:
.overlay(
HStack{
Spacer()
VStack {
Button {
dismiss()
} label: {
Image(systemName: "chevron.down.circle.fill")
.font(.largeTitle)
.foregroundStyle(.white)
}
.padding(.trailing, 20)
.padding(.top, 40)
Spacer()
}
}
)
The button will be overlaid on the scroll view, creating a floating effect. Even if you scroll down the view, the button will remain fixed in the same position. To position the button in the top right corner, we can use a combination of HStack, VStack, and Spacer. To close the view, simply call the dismiss() function.