You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI 中 ScrollView 内嵌 Map 组件出现消失问题的求助

问题根因

SwiftUI 的 Map 组件默认没有自带固定尺寸,而 ScrollView 的布局逻辑是让子视图自己决定大小,没有明确高度约束的 Map 会被系统判定为高度0,所以看起来就像消失了,和它是不是 ScrollView 的直接子组件没关系。

解决方案
  • 给 Map 加明确的高度约束
    这是最核心的修复手段,你可以按需设置固定高度(比如300),也可以结合外层的 GeometryReader 按屏幕比例设置高度,比如 proxy.size.height * 0.4 就是占屏幕可用高度的40%。
  • 统一子视图容器
    你当前代码里个人信息的 VStack 和 Map 是 ScrollView 的平级子视图,建议把它们放到同一个 VStack 里,避免出现额外的布局错乱问题。
  • 可选优化:修正交互模式配置
    你代码里的 MapInteractionModes.init() 等价于空交互模式,如果需要保留地图的缩放、拖动功能,可以替换为 .all,不需要交互保留 [] 即可。
修改后的核心代码示例

你可以直接替换原有 body 中 ScrollView 相关的代码:

var body: some View {
    GeometryReader { proxy in
        ScrollView(.vertical) {
            // 所有内容统一放到同一个VStack容器内
            VStack(spacing: 16) {
                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添加明确高度约束
                Map(coordinateRegion: $coordinateRegion, interactionModes: [], showsUserLocation: false, annotationItems: savedLocation) { annotation in
                    MapMarker(coordinate: annotation.location, tint: Color.orange)
                }
                .frame(height: 300) // 可按需调整高度值,也可替换为比例写法proxy.size.height * 0.4
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 20)
        }
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button("Edit") {
                    self.showingEditView = true
                }
            }
        }
        // 原有onAppear逻辑保留即可
        .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)
        }
    }
}

内容的提问来源于stack exchange,提问作者pakobongbong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:36:04