在 Swift 中为函数添加语句

Add a statement for a function in Swift

我有一个名为 "direction" 的标签。我有一张带有很多图钉的地图。当我点击一个图钉并点击标签 "direction" 时,它会给我两个选项并且工作正常。但是当我不点击 Pin 并点击 de label "direction" 时,应用程序崩溃了。

我想在未 select 一个 pin 时设置一个声明,提醒显示用户首先 select 一个 pin 来获取方向。

希望有人可以查看代码以实现此目的:

import UIKit
import MapKit


class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, GMSMapViewDelegate {




    @IBOutlet weak var mapView: GMSMapView!




    @IBAction func MapType(sender: AnyObject) {
        let segmentedControl = sender as! UISegmentedControl
        switch segmentedControl.selectedSegmentIndex {
        case 0:
            mapView.mapType = kGMSTypeNormal
        case 1:
            mapView.mapType = kGMSTypeSatellite
        case 2:
            mapView.mapType = kGMSTypeHybrid
        default:
            mapView.mapType = mapView.mapType
        }
    }


    let locationManager = CLLocationManager()

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        //3
        mapView.delegate = self
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

        var Marker= GMSMarker()
        Marker.position = CLLocationCoordinate2DMake(5.2317, 4.5708 )
        Marker.title = "1"
        Marker.snippet = "1"
        Marker.appearAnimation = kGMSMarkerAnimationPop
        Marker.map = mapView

        var Marker1= GMSMarker()
        Marker1.position = CLLocationCoordinate2DMake(5.2317, 8.5708 )
        Marker1.title = "2"
        Marker1.snippet = "2"
        Marker1.map = mapView      



        let label = UILabel(frame: CGRectMake(view.frame.size.width - 100, view.frame.size.height - 40, 80, 30))
        label.backgroundColor = UIColor.whiteColor()
        label.text = "direction"
        label.textAlignment = .Center
        label.layer.cornerRadius = 10
        label.clipsToBounds = true
        label.userInteractionEnabled = true

        let tap = UITapGestureRecognizer(target: self, action: "directionTapped")
        label.addGestureRecognizer(tap)




        mapView!.settings.consumesGesturesInView = false
        mapView!.addSubview(label)
        mapView!.bringSubviewToFront(label)

        self.view.addSubview(label)

    }

    func directionTapped() {
        let openMapsActionSheet = UIAlertController(title: "Open in Maps", message: "Choose a maps application", preferredStyle: .ActionSheet)
        openMapsActionSheet.addAction(UIAlertAction(title: "Apple Maps", style: .Default, handler: { (action: UIAlertAction!) -> Void in
            let placemark = MKPlacemark(coordinate: CLLocationCoordinate2DMake(self.mapView!.selectedMarker.position.latitude, self.mapView!.selectedMarker.position.longitude), addressDictionary: nil)
            let item = MKMapItem(placemark: placemark)
            let options = [MKLaunchOptionsDirectionsModeKey:
                MKLaunchOptionsDirectionsModeDriving,
                MKLaunchOptionsShowsTrafficKey: true]
            item.openInMapsWithLaunchOptions(options as [NSObject : AnyObject])
        }))
        openMapsActionSheet.addAction(UIAlertAction(title: "Google Maps", style: .Default, handler: { (action: UIAlertAction!) -> Void in
            if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
                UIApplication.sharedApplication().openURL(NSURL(string:
                    "comgooglemaps://?daddr=\(self.mapView!.selectedMarker.position.latitude),\(self.mapView!.selectedMarker.position.longitude)")!)
            } else {
                UIApplication.sharedApplication().openURL(NSURL(string:
                    "http://maps.google.com/maps?daddr=\(self.mapView!.selectedMarker.position.latitude),\(self.mapView!.selectedMarker.position.longitude)")!)
            }
        }))
        openMapsActionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        presentViewController(openMapsActionSheet, animated: true, completion: nil)
    }




    // 1
    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        // 2
        if status == .AuthorizedWhenInUse {

            // 3
            locationManager.startUpdatingLocation()

            //4
            mapView.myLocationEnabled = true
            mapView.settings.myLocationButton = true
        }
    }

    // 5
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if let location = locations.first as? CLLocation {

            // 6
            mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 6, bearing: 1, viewingAngle: 1)

            // 7
            locationManager.stopUpdatingLocation()
        }
    }





}

在没有完整代码的情况下,这是我可以推断的:

  1. 我假设您已经设置了 mapView。

  2. 我假设 mapView!.selectedMarker 仅在用户选择图钉时才会填充,否则它为 nil(或您选择的其他值),

现在,directionTapped 应该是:

if self.mapView!.selectedMarker != nil {
  <Your current Code>
} else {
  <Code to Show the new alert about pin not selected>
}

我用这段代码工作:

func directionTapped(){
    //code input from Apple-and-Oranges
            if self.mapView!.selectedMarker != nil {
    //current code
            let openMapsActionSheet = UIAlertController(title: "Open in Maps", message: "Choose a maps application", preferredStyle: .ActionSheet)
              openMapsActionSheet.addAction(UIAlertAction(title: "Apple Maps", style: .Default, handler: { (action: UIAlertAction!) -> Void in
                  let placemark = MKPlacemark(coordinate: CLLocationCoordinate2DMake(self.mapView!.selectedMarker.position.latitude, self.mapView!.selectedMarker.position.longitude), addressDictionary: nil)
                    let item = MKMapItem(placemark: placemark)
                    let options = [MKLaunchOptionsDirectionsModeKey:
                        MKLaunchOptionsDirectionsModeDriving,
                        MKLaunchOptionsShowsTrafficKey: true]
                    item.openInMapsWithLaunchOptions(options as [NSObject : AnyObject])
                }))
                openMapsActionSheet.addAction(UIAlertAction(title: "Google Maps", style: .Default, handler: { (action: UIAlertAction!) -> Void in
                  if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
                      UIApplication.sharedApplication().openURL(NSURL(string:
                        "comgooglemaps://?daddr=\(self.mapView!.selectedMarker.position.latitude),\(self.mapView!.selectedMarker.position.longitude)")!)
                   } else {
                      UIApplication.sharedApplication().openURL(NSURL(string:
                         "http://maps.google.com/maps?daddr=\(self.mapView!.selectedMarker.position.latitude),\(self.mapView!.selectedMarker.position.longitude)")!)
                   }
                }))
               openMapsActionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
               presentViewController(openMapsActionSheet, animated: true, completion: nil)
            }
    //Added a alert message
            else {


                let alertController = UIAlertController(title: "Choose Pin!", message: "\nChoose Pin to get navigation from current location", preferredStyle: .Alert)


                alertController.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
                }))

                presentViewController(alertController, animated: true, completion: nil)
            }
            }