簡體   English   中英

單擊 map 注釋時的 SwiftUI 動作

[英]SwiftUI action when clicking on map annotation

在 MapView 中單擊特定注釋時,我希望添加包含有關注釋信息的疊加層。

我正在尋找的是能夠更新一個變量,然后調用 updateUIView() 以便 map 顯示與單擊的注釋相對應的覆蓋。

你可以這樣做:

let places: [Place] = [
    .init(name: "One", coordinate: .init(latitude: 56.951924, longitude: 24.125584)),
    .init(name: "Two", coordinate: .init(latitude:  56.967520, longitude: 24.105760)),
    .init(name: "Five", coordinate: .init(latitude: 56.9539906, longitude: 24.13649290000000))
]

@State var coordinateRegion = MKCoordinateRegion(center: .init(latitude: 54.6872, longitude: 25.2797), latitudinalMeters: 2000000, longitudinalMeters: 2000000)

var body: some View {
    Map(coordinateRegion: $coordinateRegion, annotationItems: places) { (place) in
        MapAnnotation(coordinate: place.coordinate) {
            Button(action: { print(place.name) }, label: {
                Text(place.name)
            })
        }
    }
}

實現這一點的方法是跟蹤所選項目:

@State private var results: [SearchResult] = []
@State private var selectedResult: UUID?

您的項目應該已經是Identifiable ,如下所示:

struct SearchResult: Identifiable {
    let id = UUID()
    let mapItem: MKMapItem
}

然后,當您遍歷 map 注釋時,您可以決定生成選定的或未選定的注釋:

Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $trackUser, annotationItems: results) { result in
    buildAnnotation(result, isSelected: result.id == selectedResult)
}

並且在構建注釋時,添加一個輕擊手勢識別器以更改所選項目,並在需要時將 map 居中:

private func buildAnnotation(_ result: SearchResult, isSelected: Bool) -> some MapAnnotationProtocol {
    MapAnnotation(coordinate: result.mapItem.placemark.coordinate, anchorPoint: CGPoint(x: 0.5, y: 1.0)) {
        MyCustomView(isSelected: isSelected)
            .onTapGesture {
                withAnimation {
                    selectedResult = result.id
                    region.center = result.mapItem.placemark.coordinate
                }
            }
    }
}

MyCustomView只是帶有body的普通 SwiftUI View ,您可以從它所代表的項目中傳遞您想要使用的任何參數,包括它是否被選中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM