釣魚術
swift
swiftui
MapMarker
和 MapAnnotation
這兩者幾乎是一樣的,差異就在 MapAnnotation
可以客製化他的圖釘樣式PinLocation
關於那些重複出現的元件,例如在 List 或 ForEach 去迭代的內容,SwiftUI 需要識別出迭代物間的不同,因此常用的做法便是在這些元件中,插入一個獨一無二的 UUID()
,並且使之符合Identifiable
protocol。
羅志祥:翁立 翁立 友友友
翁立友:...
struct PinLocation: Identifiable {
let id = UUID()
var name: String
var image: String
var coordinate: CLLocationCoordinate2D
init(name: String, image: String, coordinate: CLLocationCoordinate2D) {
self.name = name
self.image = image
self.coordinate = coordinate
}
init() {
self.name = "秘密釣點 - 五股聖母宮"
self.image = "default"
self.coordinate = CLLocationCoordinate2D(latitude:25.1125, longitude:121.4582)
}
}
因為預計這些圖釘之間,會有不同的座標、名字、和客製化的釣點圖片,所以先把圖釘內容的格式訂成上面那樣。
MapView
程式碼struct MapView: View {
// 用來記錄長按手勢是否被觸發
@State private var isLongPressed = false
@StateObject private var viewModel = FishingLocationModel()
@State private var annotatedPin: PinLocation = PinLocation(
name: "林口發電廠", image:"", coordinate: CLLocationCoordinate2D(latitude: 25.121356, longitude: 121.295589))
@State private var annotatedPin2: PinLocation = PinLocation(
name: "林口發電廠2", image:"", coordinate: CLLocationCoordinate2D(latitude: 25.125, longitude: 121.3))
var body: some View {
ZStack(alignment: .topTrailing) {
Map(coordinateRegion: $viewModel.region,
showsUserLocation: true,
annotationItems: [annotatedPin, annotatedPin2]) { item in
// MapMarker(coordinate: item.coordinate, tint: .red)
MapAnnotation(coordinate: item.coordinate) {
Image(systemName: "hand.thumbsup.circle.fill")
.resizable()
.foregroundColor(.red)
.background(Color.white)
.clipShape(Circle())
}
}
.edgesIgnoringSafeArea(.all)
.gesture(DragGesture())
.onLongPressGesture {
isLongPressed.toggle()
}.actionSheet(isPresented: $isLongPressed) {
ActionSheet(title: Text("新增私房釣點嗎?"),
message: nil,
buttons: [
.default(Text("新增釣點")) {
// Yes
},
.cancel()
])
}
LocationButton(.currentLocation) {
viewModel.requestAllowOnceLocationPermission()
}
.foregroundColor(.white)
.cornerRadius(15)
.labelStyle(.iconOnly)
.symbolVariant(.fill)
.padding(10)
}
}
}
@State private var annotatedPin: PinLocation = PinLocation(
name: "林口發電廠", image:"", coordinate: CLLocationCoordinate2D(latitude: 25.121356, longitude: 121.295589))
PinLocation
struct,產生的實利指派給 annotatedPin
annotatedPin2