Как я могу отклонить tableView в Xcode?(Я использую searchcontroller) - PullRequest
0 голосов
/ 15 сентября 2018

Итак, я настроил карту и табличное представление с помощью searchController для поиска местоположений, и мой код должен отклонить табличное представление при нажатии на один из результатов поиска и разместить аннотацию в выбранном местоположении.Я перепробовал все перечисленное здесь:

//            self.presentingViewController?.dismiss(animated: true, completion: nil)
//            dismiss(animated: true, completion: nil)
//            self.navigationController!.dismiss(animated: true, completion: nil)
//            _ = self.navigationController?.popViewController(animated: true)
//            self.navigationController?.popViewController(animated: true)
//            viewDidDisappear(true)
//            tableView.isHidden = true
//            tableView.allowsSelection = true

Ни один из них не сработал.Вот код контроллера представления:

import UIKit
import MapKit

protocol handleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark)
}

class ViewController : UIViewController {
    let locationManager = CLLocationManager()
    var resultSearchController:UISearchController? = nil
    var selectedPin:MKPlacemark? = nil



    @IBOutlet weak var mapView: MKMapView!







override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestLocation()
    let locationSearchTable = storyboard!.instantiateViewController(withIdentifier:     "LocationSearchTable") as! LocationSearchTable
    resultSearchController = UISearchController(searchResultsController: locationSearchTable)
    resultSearchController?.searchResultsUpdater = locationSearchTable as UISearchResultsUpdating
    let searchBar = resultSearchController!.searchBar
    searchBar.sizeToFit()
    searchBar.placeholder = "Search for places"
    navigationItem.titleView = resultSearchController?.searchBar
    resultSearchController?.hidesNavigationBarDuringPresentation = false
    resultSearchController?.dimsBackgroundDuringPresentation = true
    definesPresentationContext = true
    locationSearchTable.mapView = mapView
    locationSearchTable.handleMapSearchDelegate = self

}

override func touchesBegan(_ touches: Set<UITouch>,
                           with event: UIEvent?) {
    self.view.endEditing(true)
}



}

extension ViewController : CLLocationManagerDelegate {

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("error:: \(String(describing: error.localizedDescription))")
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedWhenInUse {
        locationManager.requestLocation()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegion(center: location.coordinate, span: span)
        mapView.setRegion(region, animated: true)
    }
}



}

extension ViewController: handleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark){
    // cache the pin
    selectedPin = placemark
    // clear existing pins
    mapView.removeAnnotations(mapView.annotations)
    //mapView.removeAnnotations(mapView.annotations) 
    let annotation = MKPointAnnotation()
    annotation.coordinate = placemark.coordinate
    annotation.title = placemark.name
    if let city = placemark.locality,
        let state = placemark.administrativeArea {
        annotation.subtitle = "(\(city)) (\(state))"
    }
    mapView.addAnnotation(annotation)
    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegionMake(placemark.coordinate, span)
    mapView.setRegion(region, animated: true)
}
}

Вот код просмотра таблицы (LocationSearchTable.swift):

import UIKit
import MapKit

class LocationSearchTable : UITableViewController {
 var handleMapSearchDelegate:handleMapSearch? = nil
var matchingItems:[MKMapItem] = []
var mapView: MKMapView? = nil




func parseAddress(selectedItem: MKPlacemark) -> String {
    // put a space between "4" and "Melrose Place"
    let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : ""
    // put a comma between street and city/state
    let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : ""
    // put a space between "Washington" and "DC"
    let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : ""
    let addressLine = String(
        format:"%@%@%@%@%@%@%@",
        // street number
        selectedItem.subThoroughfare ?? "",
        firstSpace,
        // street name
        selectedItem.thoroughfare ?? "",
        comma,
        // city
        selectedItem.locality ?? "",
        secondSpace,
        // state
        selectedItem.administrativeArea ?? ""
    )
    return addressLine
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return matchingItems.count - 1
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell") as!
    ResultsDisplayCell

    let selectedIndex = self.matchingItems[indexPath.row]


    cell.titleLabel?.text = selectedIndex.placemark.title
    cell.detailTextLabel?.text = selectedIndex.name
    //cell.detailTextLabel?.text = selectedIndex.placemark.subThoroughfare
    //cell.detailTextLabel?.text = selectedIndex.name
    //cell.detailTextLabel?.text = selectedIndex.placemark.subtitle
    return cell
}

}




extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {

    guard let mapView = mapView,
            let searchBarText = searchController.searchBar.text else { return }
        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = searchBarText
        request.region = mapView.region
        let search = MKLocalSearch(request: request)
        search.start { response, _ in
            guard let response = response else {
                return
            }

            for mapItems in response.mapItems{
                self.matchingItems.append(mapItems as MKMapItem)
                print("thisisthearray:\(self.matchingItems)")



            self.matchingItems = response.mapItems
            self.tableView.reloadData()

}



}
}

}



extension LocationSearchTable {
    func tableView(tableView: UITableView, didSelectRowAt indexPath: NSIndexPath) {
    let selectedItem = matchingItems[indexPath.row].placemark
        handleMapSearchDelegate?.dropPinZoomIn(placemark: selectedItem)
        self.dismiss(animated: true, completion: nil)

        tableView.keyboardDismissMode = .onDrag // .interactive
//            self.presentingViewController?.dismiss(animated: true, completion: nil)
//            dismiss(animated: true, completion: nil)
//            self.navigationController!.dismiss(animated: true, completion: nil)
//            _ = self.navigationController?.popViewController(animated: true)
//            self.navigationController?.popViewController(animated: true)
//            viewDidDisappear(true)
//            tableView.isHidden = true
//            tableView.allowsSelection = true

}




}

Был бы очень признателен за помощь:)

1 Ответ

0 голосов
/ 17 сентября 2018

В вашем расширении LocationSearchTable правильная подпись для функции делегата табличного представления:

func tableView(_ tableView: UITableView, 
         didSelectRowAt indexPath: IndexPath) 

Затем, адаптируя этот ответ переполнения стека для вашего примера, вы можете попробовать следующим образом:

  • вызовите dismiss в функции didSelectRow вашего контроллера представления LocationSearchTable
  • при получении обратного вызова делегата handleMapSearch задайте свойству isActive контроллера поиска значение false

    extension LocationSearchTable {
        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let selectedItem = matchingItems[indexPath.row].placemark
            self.dismiss(animated: true, completion: {
                self.handleMapSearchDelegate?.dropPinZoomIn(placemark: selectedItem)
            })
        }
    }
    
    extension ViewController: handleMapSearch {
        func dropPinZoomIn(placemark:MKPlacemark) {
            resultSearchController?.isActive = false
    
            // cache the pin
            selectedPin = placemark
            // clear existing pins
            mapView.removeAnnotations(mapView.annotations)
            let annotation = MKPointAnnotation()
            annotation.coordinate = placemark.coordinate
            annotation.title = placemark.name
            if let city = placemark.locality,
                let state = placemark.administrativeArea {
                annotation.subtitle = "(\(city)) (\(state))"
            }
            mapView.addAnnotation(annotation)
            let span = MKCoordinateSpanMake(0.05, 0.05)
            let region = MKCoordinateRegionMake(placemark.coordinate, span)
            mapView.setRegion(region, animated: true)
        }
    }
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...