在Swift中为函数添加语句

时间:2015-07-20 12:15:50

标签: ios swift uitapgesturerecognizer

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

我想设置一个声明,当没有选择一个引脚时,警告显示用户首先选择一个引脚来获取路线。

希望有人可以查看代码来实现这一目标:

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()
        }
    }





}

2 个答案:

答案 0 :(得分:1)

这段代码对我有用:

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)
            }
            }

答案 1 :(得分:0)

如果没有完整的代码,我可以推断:

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

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

  3. 现在,directionTapped应为:

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