課程筆記文集地址:Udemy課程:The Complete iOS 9 Developer Course - Build 18 Apps
一卸亮、創(chuàng)建并添加圖釘
// 創(chuàng)建一個(gè)圖釘實(shí)例
var annotation = MKPointAnnotation()
//圖釘?shù)淖鴺?biāo)信息
annotation.coordinate = location
//圖釘?shù)臉?biāo)題
annotation.title = "某某某某某某"
//圖釘?shù)母睒?biāo)題
annotation.subtitle = "有一天我要到這個(gè)地方去"
//把圖釘添加到地圖上
map.addAnnotation(annotation)
就這么簡(jiǎn)單厚掷,一個(gè)圖釘就添加到地圖上啦~
二愕贡、給地圖添加長(zhǎng)按手勢(shì)
長(zhǎng)按地圖的某個(gè)地方,然后會(huì)在這個(gè)點(diǎn)創(chuàng)建一個(gè)圖釘论矾。要實(shí)現(xiàn)這個(gè)需求驮宴,首先要給地圖添加一個(gè)長(zhǎng)按手勢(shì):
//創(chuàng)建長(zhǎng)按手勢(shì)實(shí)例,這里長(zhǎng)按后的動(dòng)作都在方法 `action:` 里秽晚,冒號(hào)表示方法有參數(shù)
var longPressGesture = UILongPressGestureRecognizer(target: self, action: "action:")
//定義多長(zhǎng)時(shí)間就可以算是長(zhǎng)按了
longPressGesture.minimumPressDuration = 2
//把這個(gè)長(zhǎng)按手勢(shì)添加到地圖上
map.addGestureRecognizer(longPressGesture)
接下來(lái)實(shí)現(xiàn)長(zhǎng)按后要執(zhí)行的方法:
func action(gestureRecognizer: UIGestureRecognizer) {
//可以在這里實(shí)現(xiàn)長(zhǎng)按后想要實(shí)現(xiàn)的一些事情
}
三瓦糟、長(zhǎng)按地圖上的某個(gè)點(diǎn)添加一個(gè)圖釘
func action(gestureRecognizer: UIGestureRecognizer) {
//記錄用戶(hù)長(zhǎng)按所在的點(diǎn)的位置
var touchPoint = gestureRecognizer.locationInView(self.map)
//將手指所在的點(diǎn)的位置轉(zhuǎn)換成地圖上的2D坐標(biāo)數(shù)值
var newCoordinate: CLLocationCoordinate2D = map.convertPoint(touchPoint, toCoordinateFromView: self.map)
//這之后的代碼都是在 一、創(chuàng)建并添加圖釘 里說(shuō)過(guò)的代碼
var annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate
annotation.title = "New Place"
annotation.subtitle = "One day I'll go here..."
map.addAnnotation(annotation)
}
運(yùn)行程序赴蝇,在地圖上長(zhǎng)按某個(gè)點(diǎn)菩浙,這個(gè)點(diǎn)就會(huì)出現(xiàn)一個(gè)圖釘。不過(guò)圖釘?shù)男畔⒉荒芫庉嫞际悄J(rèn)的劲蜻,如何才能讓用戶(hù)自定義某個(gè)圖釘?shù)?title 和 subtitle 呢陆淀?在之后的課程里會(huì)講到的~