iOS Swift: SearchController with a StoryBoard UISearchBar



晚上,我构建了一个搜索控制器,我也有以编程方式创建搜索的代码。但我想用故事板中设计的搜索栏替换此代码。

所以我的问题是,如何将插座连接到搜索控制器?

这是我的代码:

public class CustomSearchController: UISearchController {
    public var customSearchBar = UISearchBar()
    override public var searchBar: UISearchBar {
        get {
            return self.customSearchBar
        }
    }
}
func configureSearchController() {
    searchController = CustomSearchController()
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.customSearchBar = self.customSearchBar
    searchController.searchBar.delegate = self
    self.definesPresentationContext = true
}
extension EarthSearcherTableViewController : UISearchResultsUpdating {
    public func updateSearchResults(for searchController: UISearchController) {
        //Code
        guard let text = searchController.searchBar.text else { return }
        self.getLocations(forSearchString: text)
    }
    fileprivate func getLocations(forSearchString searchString: String) {
        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = searchString
        request.region = mapView.region
        let search = MKLocalSearch(request: request)
        search.start { (response, error) in
            guard let response = response else { return }
            self.locations = response.mapItems
            self.tableView.reloadData()
        }
    }
    @objc func zoomToCurrentLocation() {

        //Clear existing pins
        mapView.removeAnnotations(mapView.annotations)
        mapView.removeOverlays(mapView.overlays)
        let annotation = MKPointAnnotation()
        annotation.coordinate = mapView.userLocation.coordinate
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.005, 0.005)
        let region = MKCoordinateRegionMake(mapView.userLocation.coordinate, span)
        mapView.setRegion(region, animated: true)
        let location = CLLocation(latitude: mapView.userLocation.coordinate.latitude, longitude: mapView.userLocation.coordinate.longitude)
        mapView.add(MKCircle(center: location.coordinate, radius: 50))

    }
}

我想我对代表有问题,因为当我在搜索栏中输入时,结果不会在表格中显示

有什么提示吗?

>子类UISearchController并覆盖searchBar getter以返回所需的搜索栏。

public class mySearchController: UISearchController {
    public var customSearchBar = UISearchBar()
    override public var searchBar: UISearchBar {
        get {
            return customSearchBar
        }
    }
}

在您的方法中,将customSearchBar设置为您的searchBar

func configureSearchController() {    
    searchController = mySearchController()
    searchController.customSearchBar = self.searchBar
    //Other stuff...
}

最新更新