-3

我正在尝试利用多个教程来自学 Swift。

到目前为止,我有这个代码。

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate
{
    @IBOutlet weak var myMapView: MKMapView!

    var manager:CLLocationManager!
    var myLocations: [CLLocation] = []

    @IBOutlet weak var textView: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Setup our Location Manager
        manager = CLLocationManager()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()

        textView.delegate = self

        //Setup our Map View
        myMapView.delegate = self
        myMapView.mapType = MKMapType.Satellite
        myMapView.showsUserLocation = true
    }

    func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
        //theLabel.text = "\(locations[0])"
        myLocations.append(locations[0] as CLLocation)

        let spanX = 0.007
        let spanY = 0.007
        var newRegion = MKCoordinateRegion(center: myMapView.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
        myMapView.setRegion(newRegion, animated: true)

        if (myLocations.count > 1){
            var sourceIndex = myLocations.count - 1
            var destinationIndex = myLocations.count - 2

            let c1 = myLocations[sourceIndex].coordinate
            let c2 = myLocations[destinationIndex].coordinate
            var a = [c1, c2]
            var polyline = MKPolyline(coordinates: &a, count: a.count)
            myMapView.addOverlay(polyline)
        }

    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        var annotation = CustomAnnotation(coordinate: manager.location, title: textView.text, subtitle: "SubTitle");
        myMapView.addAnnotation(annotation)
        textView.resignFirstResponder()
        return true
    }
}

这条线

var annotation = CustomAnnotation(coordinate: manager.location, title: textView.text, subtitle: "SubTitle");

导致此错误:

'CLLocation' 不能转换为 'CLLocationCoordinate2D'

我的另一个 Swift 文件是:

import UIKit
import MapKit

class CustomAnnotation: NSObject, MKAnnotation {

    var coordinate:CLLocationCoordinate2D
    var title:NSString!
    var subtitle: NSString!

    init(coordinate: CLLocationCoordinate2D, title: NSString!, subtitle: NSString!) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }

}
4

2 回答 2

2

错误消息相当明确。init想要 a而CLLocationCoordinate2D你却试图给它 a CLLocation。我怀疑你想传递的coordinate属性manager.location而不是位置本身。

于 2015-04-20T13:15:13.200 回答
1

CLLocation 有一个名为“coordinate”的 CLLocationCoordinate2D 类型的属性,因此您可以访问该字段并获取 CLLocation 的 CLLocationCoordinate2D

于 2017-02-16T05:13:52.647 回答