如何设置操作来搜索的取消按钮
问题描述:
我有我的mapView搜索功能,所以你可以搜索注释。 我想添加一个选项,当我按下取消按钮时,用户位置的trackingMode将为真 ,因此地图将再次以用户位置为中心。如何做呢? 这里是我的搜索代码:如何设置操作来搜索的取消按钮
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!
}
感谢帮助 希望有人能解决了我的问题
答
假设你指的是搜索栏的取消按钮,您需要实现在该searchBarCancelButtonClicked委托方法主viewController。根据我发布到GitHub的代码,将此方法添加到ViewController.swift。
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
updateMap(CLLocation(latitude: currentLoc.coordinate.latitude, longitude: currentLoc.coordinate.longitude))
}
此外,声明currentLocation viewDidLoad中
var currentLoc:MKPointAnnotation!
的外部。如果我实现这个取消按钮仍然会取消搜索,此外将放大用户的位置吗?我在回家的路上,我会很快测试代码。 –
是的,它会取消搜索并放大当前位置。 –
有一个选项,当你按结果它会放大正确的引脚,并自动打开注解查看 –