如何设置搜索取消按钮的操作

时间:2017-04-20 21:35:11

标签: ios swift uibutton mkmapview

我的mapView具有搜索功能,因此您可以搜索注释。 我想添加一个选项,当我按下取消按钮时,用户位置的trackingMode将为true ,因此地图将再次以用户位置为中心。怎么做到呢? 这是我的搜索代码:

   override func viewDidLoad() {
        super.viewDidLoad()

        //==========RegionLocation : =========

        // Init the zoom level
        let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 31.30, longitude: 34.45)
        let span = MKCoordinateSpanMake(125, 125)
        let region = MKCoordinateRegionMake(coordinate, span)
        self.mapView.setRegion(region, animated: true)


        //====================================\\



        //==============Tel Aviv==============
        self.mapView.delegate = self
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true


         // Drop a pin
        let LitzmanLocation = CLLocationCoordinate2DMake(32.100668,34.775192)
        let Litzman = MKPointAnnotation()
        Litzman.coordinate = LitzmanLocation
        Litzman.title = "Litzman Bar"
        Litzman.subtitle = "נמל תל אביב 18,תל אביב"
        mapView.addAnnotation(Litzman)
 let searchTable = storyboard!.instantiateViewController(withIdentifier: "SearchTableViewController") as! SearchTableViewController

        searchController = UISearchController(searchResultsController: searchTable)
        searchController?.searchResultsUpdater = searchTable
        searchController?.hidesNavigationBarDuringPresentation = false
        searchController?.dimsBackgroundDuringPresentation = true

            definesPresentationContext = true

            let searchBar = searchController!.searchBar
            searchBar.sizeToFit()
            searchBar.placeholder = "חפש ברים"
            navigationItem.titleView = searchController?.searchBar
            searchBar.delegate = self

            searchTable.mapView = mapView
            searchTable.handleMapSearchDelegate = self
    }
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])


    {
        let location = locations.last

        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.06, longitudeDelta: 0.06))

        self.mapView.setRegion(region, animated: true)

        self.locationManager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Errors: " + error.localizedDescription)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            return nil
        }
        let reuseID = "pin"

        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID) as? MKPinAnnotationView
        if(pinView == nil) {
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
            pinView!.canShowCallout = true
            pinView!.animatesDrop = false
            pinView!.image = UIImage (named: "")
            pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIButton
            let smallSquare = CGSize(width: 40, height: 40)
            let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
            button.setBackgroundImage(UIImage(named: "Car2"), for: UIControlState())
            pinView?.leftCalloutAccessoryView = button

        }
        else
        {
            pinView?.annotation = annotation
        }

        return pinView

    }


    func openMapsAppWithDirections(to coordinate: CLLocationCoordinate2D, destinationName name: String) {
        let options = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
        let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = name // Provide the name of the destination in the To: field
        mapItem.openInMaps(launchOptions: options)


        func openMapsAppWithDirections(_ latitude: Double, longitude: Double) {
            if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                //Waze is installed. Launch Waze and start navigation
                let urlStr = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                UIApplication.shared.openURL(URL(string: urlStr)!)
            }
            else {
                //Waze is not installed. Launch AppStore to install Waze app
                UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
            }
        }



    }

    func mapView(_ MapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped controll: UIControl) {
        if controll == annotationView.rightCalloutAccessoryView {
            let segueID: String = "BarsProfile" // Use the appropriate segue ID here
            performSegue(withIdentifier: segueID, sender: self)}

            if controll == annotationView.leftCalloutAccessoryView {
                if let annotation = annotationView.annotation {
                    // Unwrap the double-optional annotation.title property or
                    // name the destination "Unknown" if the annotation has no title
                    let destinationName = (annotation.title ?? nil) ?? "Unknown"
                    openMapsAppWithDirections(to: annotation.coordinate, destinationName: destinationName)


                        }
                    }
            }
    func updateMap(_ location: CLLocation)  {
        let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 150, 150)
        mapView.setRegion(region, animated: true)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        print("Cancel!")
        updateMap(CLLocation(latitude: currentLoc.coordinate.latitude, longitude: currentLoc.coordinate.longitude))
    }

}



extension MapViewController: HandleMapSearch   {
    func dropPinZoomIn(placemark: MKAnnotation)    {
        updateMap(CLLocation(latitude: placemark.coordinate.latitude, longitude: placemark.coordinate.longitude))
        searchController.searchBar.text = placemark.title!
    }

感谢您的帮助 希望有人能解决我的问题

1 个答案:

答案 0 :(得分:2)

假设您指的是searchBar的取消按钮,您需要在主viewController中实现searchBarCancelButtonClicked委托方法。根据我发布到GitHub的代码,将此方法添加到ViewController.swift。

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    updateMap(CLLocation(latitude: currentLoc.coordinate.latitude, longitude: currentLoc.coordinate.longitude))
}

另外,在viewDidLoad

之外声明currentLocation
var currentLoc:MKPointAnnotation!
相关问题