UISearchController 结果 TableViewController 在 UISearchBar 为空时不清除结果
UISearchController results TableViewController doesn't clear results when UISearchBar is empty
我不擅长 iOS 开发并且卡在了一个简单的问题上。
我正在尝试创建一个 UISearchController,它在结果的 backgroundView 中有一条空消息 tableView 首次启动时或 UISearchBar 为空时(无论是退格,点击 x 清除字段,或从 UISearchBar 中取消)。
当 UISearchBar 第一次聚焦时,我已经完成了添加空消息,但是在搜索发生后,旧的搜索结果仍然在结果 table 视图中,在我取消搜索和清空后UISearchBar.
我认为情况一直如此,但我以前没有看到旧的结果,而现在我设置 searchController.searchResultsController?.view.isHidden = false
以便在控制器首次启动时能够看到背景。
我进行了相当广泛的搜索,只是想不出如何清除旧结果。
我的整个结果表ViewController代码:
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
}
}
以及实现 UISearchController 的主要 ViewController 中的相关(我认为)UISearchBar 代码:
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
}
}
}
这是您需要清除 dataArray 的方法.. 并在 tableView
上调用 reloadData()
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
searchResults.removeAll()
tableView.reloadData()
}
}
我不擅长 iOS 开发并且卡在了一个简单的问题上。
我正在尝试创建一个 UISearchController,它在结果的 backgroundView 中有一条空消息 tableView 首次启动时或 UISearchBar 为空时(无论是退格,点击 x 清除字段,或从 UISearchBar 中取消)。
当 UISearchBar 第一次聚焦时,我已经完成了添加空消息,但是在搜索发生后,旧的搜索结果仍然在结果 table 视图中,在我取消搜索和清空后UISearchBar.
我认为情况一直如此,但我以前没有看到旧的结果,而现在我设置 searchController.searchResultsController?.view.isHidden = false
以便在控制器首次启动时能够看到背景。
我进行了相当广泛的搜索,只是想不出如何清除旧结果。
我的整个结果表ViewController代码:
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
}
}
以及实现 UISearchController 的主要 ViewController 中的相关(我认为)UISearchBar 代码:
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
}
}
}
这是您需要清除 dataArray 的方法.. 并在 tableView
reloadData()
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
searchResults.removeAll()
tableView.reloadData()
}
}