I want to display a sheet on top of a Map
in SwiftUI. The following is a simplified example:
class ItemAnnotation: NSObject, MKAnnotation {
private(set) var coordinate: CLLocationCoordinate2D
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
}
}
struct Item: Identifiable {
let id = UUID()
let coord: CLLocationCoordinate2D
}
struct ContentView: View {
@State private var showSheet = false
var body: some View {
TabView {
VStack {
Map(coordinateRegion: .constant(MKCoordinateRegion(MKMapRect.world)), annotationItems: items()) { item in
MapMarker(coordinate: item.coord)
}
Button("Toggle Sheet") {
showSheet.toggle()
}
.padding()
}.sheet(isPresented: $showSheet, content: {
Text("some text")
})
}
}
private func items() -> [Item] {
var res = [Item]()
stride(from: -20, through: 20, by: 1).forEach { lat in
stride(from: -50, through: 100, by: 5).forEach { long in
res.append(Item(coord: CLLocationCoordinate2D(latitude: lat, longitude: long)))
}
}
return res
}
}
Unfortunately the above code produces a hang every time I open/close the Sheet.
The hang doesn't occur, if I remove the TabView
and display only the VStack
:
struct ContentView: View {
@State private var showSheet = false
var body: some View {
VStack {
Map(coordinateRegion: .constant(MKCoordinateRegion(MKMapRect.world)), annotationItems: items()) { item in
MapMarker(coordinate: item.coord)
}
Button("Toggle Sheet") {
showSheet.toggle()
}
.padding()
}.sheet(isPresented: $showSheet, content: {
Text("some text")
})
}
// ...
}
If I replace the TabView
with a NavigationStack
the behaviour is the same.
In the real project I use a MKMapView
as an UIViewRepresentable
to be able to use clustering. But since the problem even occurs with Map
I guess it's the same root cause. I suspect it's somehow related to the way a view is reloaded / redrawn if it's embedded inside a TabView
/ NavigationStack
.
How can I avoid the hang while still using a TabView
(that's mandatory for the real project)?