我試圖給用戶輸入地址並讓地圖縮放到其中的能力。當使用MapKit時,可以在Swift中使用可拖動的註釋
我想讓用戶將別針拖到另一個位置,然後獲取位置信息並將其用於任何內容。
我試過了,我試過了,但是我可以開始工作的最多的是將實際的針腳更改爲自定義圖像。我已經閱讀了幾篇文章和教程(全部爲Objective-c),即使在轉換代碼之後,我仍然無法使其工作。
我的自定義註解視圖:
import Foundation
import MapKit
class CustomAnnotationView: MKAnnotationView {
var coordinate:CLLocationCoordinate2D!
init(coordinate:CLLocationCoordinate2D) {
super.init()
self.coordinate = coordinate
}
override init(frame: CGRect) {
super.init(frame: CGRect())
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(annotation: MKAnnotation!, reuseIdentifier: String!) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
image = UIImage(named: "pin")
draggable = true
canShowCallout = true
}
func setCoordinate(newCoordinate: CLLocationCoordinate2D){
self.coordinate = newCoordinate;
}
}
我的控制器,裏面我的MapView:
import Foundation
import MapKit
class LocationViewController : UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var searchField: UITextField!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var locationInstructions: UITextView!
@IBAction func didTapGoButton(sender: UIButton) {
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(searchField.text, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
if let placemark = placemarks?[0] as? CLPlacemark {
var region = self.mapView.region as MKCoordinateRegion
region.center = placemark.location.coordinate
region.span.longitudeDelta /= 30.0;
region.span.latitudeDelta /= 30.0;
self.mapView.zoomEnabled = true
self.mapView.scrollEnabled = true
self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
self.mapView.setRegion(region, animated: true)
}
})
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation.isKindOfClass(MKUserLocation) {
return nil
}
var pin = mapView.dequeueReusableAnnotationViewWithIdentifier("CustomAnnotationView")
if pin == nil {
NSLog("PIN NIL")
pin = CustomAnnotationView(annotation: annotation, reuseIdentifier: "CustomAnnotationView")
}
else
{
NSLog("PIN NOT NIL")
pin.annotation = annotation;
}
return pin;
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
if newState == MKAnnotationViewDragState.Starting
{
view.dragState = MKAnnotationViewDragState.Dragging
}
else if newState == MKAnnotationViewDragState.Ending || newState == MKAnnotationViewDragState.Canceling
{
view.dragState = MKAnnotationViewDragState.None;
}
}
我缺少什麼?
我找不到任何成功完成這個任務的Swift示例。
擺脫了CustomAnnotationView。一切正常,但有一件事已經改變。當我點擊引腳時,它通常顯示我輸入的郵政編碼區域的名稱。但現在它顯示我輸入到文本區域的內容。無論如何顯示關於引腳被繪製的詳細信息? – LondonGuy 2014-09-14 04:33:29
好吧搞亂pa.title = placemark.locality等幫助。我想我可以連接一些字符串。我會看看我的選擇。謝謝您的幫助 – LondonGuy 2014-09-14 04:40:59