SwiftUI 中的地图和滚动视图

Map and Scrollview in SwiftUI

我试图将地图显示为 ScrollView 的一部分,但 ScrollView 似乎只会导致地图消失。无论 Map 是 ScrollView 的子级还是其他,都会发生这种情况。

有什么建议吗? (请原谅我的代码真的很糟糕,我正在学习。)

struct DetailView: View {
    @ObservedObject var person: Person
    @State private var data = Data()
    @State private var showingEditView = false
    @State private var savedLocation: [SavedLocation] = []
    @State private var coordinateRegion = MKCoordinateRegion()
    @State private var annotation = MapMarker(coordinate: CLLocationCoordinate2D(), tint: Color.orange)
    var body: some View {
        GeometryReader { proxy in
            ScrollView(.vertical) {
                VStack {
                    Image(uiImage: UIImage(data: self.data) ?? UIImage())
                        .resizable()
                        .scaledToFit()
                        .frame(maxWidth: proxy.size.width * 0.7)
                        .clipShape(Circle())
                        .overlay(Circle().stroke(Color.white, lineWidth: 1))
                        .shadow(radius: 5)
                    
                    Text(person.name ?? "")
                    Text(person.email ?? "")
                    Text(person.phoneNumber ?? "")
                    Text(person.notes ?? "")
                }
                
                Map(coordinateRegion: $coordinateRegion, interactionModes: MapInteractionModes.init(), showsUserLocation: false, userTrackingMode: nil, annotationItems: savedLocation) { annotation in
                    MapMarker(coordinate: annotation.location, tint: Color.orange)
                }
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Edit") {
                        self.showingEditView = true
                    }
                }
            }
            .onAppear {
                ProfilePictureLoader.getProfilePicture(using: person.id!) { result in
                    switch result {
                    case .success(let data):
                        self.data = data
                    case .failure(let error):
                        print("\(error.localizedDescription)")
                    }
                }
                self.coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: person.coordinate!.latitude, longitude: person.coordinate!.longitude), latitudinalMeters: 200, longitudinalMeters: 200)
                let savedLocation = SavedLocation(id: person.id!, lat: person.coordinate!.latitude, long: person.coordinate!.longitude)
                self.savedLocation.append(savedLocation)
            }
        }
    }
}

ScrollView 获取所有可用的 space 并且不对子视图施加大小限制。因为 Map 的行为类似,没有来自父级的大小限制,在 ScrollView 内,它可以完全崩溃(例如 0,0 的框架)。

要解决此问题,您可以向地图添加一个明确的 frame 修饰符以告知其大小:

Map(...) { ... }.frame(width: 300, height: 300)