当UISearchBar为空时,UISearchController结果TableViewController不清除结果。

问题描述 投票:1回答:1

我不擅长iOS开发,被一个简单的问题卡住了。

我试图创建一个UISearchController,当UISearchController第一次启动时,或者当UISearchBar为空时(无论是从后置间距、点击x来清除字段,还是从UISearchBar中取消),在结果表View的背景View中有一条空消息。

我已经完成了在UISearchBar第一次被关注时添加空信息的任务,但是在搜索发生后,当我取消搜索和清空UISearchBar后,旧的搜索结果仍然在结果表视图中。

我想这种情况一直都存在,但是我之前一直没有看到旧的结果,而现在我设置了 searchController.searchResultsController?.view.isHidden = false 以便在控制器第一次启动时能够看到背景。

我找了很久,就是想不出如何清除旧结果。

我的整个结果TableViewController代码。

import UIKit
import MapKit
import Mapbox

class LocationSearchTableViewController: UITableViewController {

    var matchingItems: [MKMapItem] = []
    var mapView: MGLMapView? = nil

    // This somehow connects and pleases the delegate
    var handleMapSearchDelegate: HandleMapSearch? = nil

    // Address formatting, not entirely sure what this is doing
    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
    }
}

// Extension with UISearchResultsUpdating delegate protocols
extension LocationSearchTableViewController: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {

        // This unhides the results view so it's visible when the field is focused
        searchController.searchResultsController?.view.isHidden = false

        // Get searchbar text and make query
        guard let _ = mapView,
            let searchBarText = searchController.searchBar.text else { return }
        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = searchBarText
        let search = MKLocalSearch(request: request)

        search.start { response, _ in
            guard let response = response else {
                return
            }
            self.matchingItems = response.mapItems
            self.tableView.reloadData()
        }

        if searchBarText == "" {
//            searchResults.removeAll()
            tableView.reloadData()
        }
    }
}

// Extension with all UITableViewDataSource methods grouped together
extension LocationSearchTableViewController {

    // Create rows based on number of returning items
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if matchingItems.count == 0 {
            setEmptyMessage()
        } else {
            restore()
        }


        return matchingItems.count
    }


    // Populate cells
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        let selectedItem = matchingItems[indexPath.row].placemark
        cell.textLabel?.text = selectedItem.name
        cell.detailTextLabel?.text = parseAddress(selectedItem: selectedItem)

        return cell
    }
}

// Groups UITableViewDelegate methods together
extension LocationSearchTableViewController {

    // Function that fires on tapping a row
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // Assign placemark value (coordinates)
        let selectedItem = matchingItems[indexPath.row].placemark


        // Delegate function that passes placemark
        handleMapSearchDelegate?.dropPin(placemark: selectedItem)

        // Dismiss searchController
        dismiss(animated: true, completion: nil)
    }
}

extension LocationSearchTableViewController {

    func setEmptyMessage() {
        let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height))
        let messageLabel = UILabel(frame: rect)
        messageLabel.text = "Empty"
        messageLabel.textColor = .black
        messageLabel.numberOfLines = 0
        messageLabel.textAlignment = .center
        messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
        messageLabel.sizeToFit()

        self.tableView.backgroundView = messageLabel
        //            self.tableView.backgroundView?.isHidden = false
        self.tableView.backgroundColor = Colors.black1
        self.tableView.separatorStyle = .none
    }

    func restore() {
        self.tableView.backgroundView = nil
        self.tableView.separatorStyle = .singleLine
    }
}

还有相关的(我想)UISearchBar代码,来自实现UISearchController的主ViewController。

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

        if let navigationController = navigationController { // this unwraps navigation controller
            navigationController.setNavigationBarHidden(true, animated: true)
            UIView.animate(withDuration: 1) {
                self.placeholderView.alpha = 0
            }
        }
    }
ios swift tableview uisearchcontroller
1个回答
2
投票

这里是你需要清除你的dataArray的方法......并调用。reloadData() 在你 tableView

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
      if searchText.isEmpty {

                searchResults.removeAll()
                tableView.reloadData()

      }
  }
© www.soinside.com 2019 - 2024. All rights reserved.