iOS Swift:带有StoryBoard UISearchBar的SearchController

时间:2017-03-28 13:06:10

标签: ios swift 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))


    }

}

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

任何提示?

1 个答案:

答案 0 :(得分:3)

子类UISearchController并覆盖searchBar getter以返回您想要的searchBar。

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