我正在关注本教程:https://www.raywenderlich.com/4363809-uisearchcontroller-tutorial-getting-started
这是相关的代码。 唯一的问题是搜索栏不可见。在本教程中,他创建了一个UISearchController,奇迹般地出现了搜索栏(尽管它不在情节提要中的任何地方,所以我无法解释它对他的工作原理):
import UIKit
import RealmSwift
class PlacesViewController: UIViewController{
@IBOutlet weak var tableView: UITableView!
var places11:Results<Place11>?
let searchController = UISearchController(searchResultsController: nil)
var filteredPlaces: [Place11] = []
override func viewDidLoad() {
super.viewDidLoad()
places11 = PlaceService.getPlaces11()
tableView.delegate = self
tableView.dataSource = self
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Permits"
navigationItem.searchController = searchController
definesPresentationContext = true
}
func filterContentForSearchText(_ searchText: String) {
let array = places11?.toArray(type: Place11.self)
filteredPlaces = array!.filter { (place: Place11) -> Bool in
let bool2 = (place.description.lowercased().contains(searchText.lowercased()) )
return bool2
}
tableView.reloadData()
}
var isSearchBarEmpty: Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
var isFiltering: Bool {
return searchController.isActive && !isSearchBarEmpty
}
}
extension PlacesViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
let text = searchBar.text!
filterContentForSearchText(text)
}
}
答案 0 :(得分:0)
使搜索栏出现在导航栏中的是此行:
navigationItem.searchController = searchController
问题是您的视图控制器不属于导航界面。没有导航控制器,也没有导航栏,因此搜索栏无处可寻。