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

SwiftUI中Map标注的onLongPressGesture未触发,Sheet无法弹出

解决SwiftUI Map标注长按手势不触发的问题

问题核心是Map组件默认的Annotation交互会拦截长按手势——默认状态下,点击Annotation会触发显示标题的内置行为,这个交互优先级高于你给自定义标注视图添加的长按手势,导致你的手势无法被识别。

解决步骤

  1. 关闭Map的默认Annotation标题交互,让手势能传递到自定义标注视图上
  2. 确保长按手势的绑定逻辑正确

修改后的完整代码

import SwiftUI
import MapKit

struct ContentView: View {
    @State private var userLocations = [UserLocation]()
    @State private var selectedPlace: UserLocation? = nil
    
    let startPosition = MapCameraPosition.region(
        MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: 42.196, longitude: 24.747),
            span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10)
        )
    )
    
    var body: some View {
        MapReader { proxy in
            // 添加 annotationTitles: .hidden 关闭默认标题交互
            Map(initialPosition: startPosition, annotationTitles: .hidden) {
                ForEach(userLocations) { location in
                    Annotation(location.name, coordinate: location.coordinate) {
                        Image(systemName: "star.circle")
                            .resizable()
                            .foregroundStyle(.red)
                            .frame(width: 44, height: 44)
                            .background(.white)
                            .clipShape(Circle())
                            .onLongPressGesture {
                                print("长按触发")
                                selectedPlace = location
                            }
                    }
                }
            }
            .onTapGesture { position in
                if let coordinate = proxy.convert(position, from: .local) {
                    let newLocation = UserLocation(
                        id: UUID(),
                        name: "New Location",
                        description: "",
                        latitude: coordinate.latitude,
                        longitude: coordinate.longitude
                    )
                    userLocations.append(newLocation)
                }
            }
            .sheet(item: $selectedPlace) { place in
                Text(place.name)
            }
        }
    }
}

struct UserLocation: Codable, Equatable, Identifiable {
    let id: UUID
    var name: String
    var description: String
    var latitude: Double
    var longitude: Double
    
    var coordinate: CLLocationCoordinate2D {
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

额外说明

如果需要自定义长按的触发时长,可以给onLongPressGesture添加参数调整,示例:

.onLongPressGesture(minimumDuration: 0.5) {
    selectedPlace = location
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:55:59