我正在学习UISearchController,发现我遇到了以下问题。
当我在搜索栏中键入文本时,




class Method2VC: UIViewController {
@IBOutlet weak var tableView: UITableView!
var item = [Item]()
var searchResults = [Item]()
var searchController: UISearchController!
var isSearchBarEmpty: Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
// Setup Search Bar information
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = true
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = true
searchController.searchBar.placeholder = "输入搜索信息"
searchController.definesPresentationContext = true
fetchData()
}
func fetchData() {
let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest()
// let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
let modelSort = NSSortDescriptor(key: "model", ascending: true)
fetchRequest.sortDescriptors = [modelSort]
do {
let fetchedResults = try context.fetch(fetchRequest)
item = fetchedResults
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let destinationController = segue.destination as! DetailVC
destinationController.item = !isSearchBarEmpty ? searchResults[indexPath.row] : item[indexPath.row]
}
}
}
}
// MARK: - UITableView Datasource
extension Method2VC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !isSearchBarEmpty {
return searchResults.count
} else {
return item.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
// Determine the data - Original Data or SearchResults Data
let model = !isSearchBarEmpty ? searchResults[indexPath.row] : item[indexPath.row]
// Configure Cell
cell.textLabel?.text = model.model
return cell
}
}
// MARK: - UISearchResultUpdating
extension Method2VC: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
if !isSearchBarEmpty {
if let searchText = searchController.searchBar.text {
filterContent(for: searchText)
tableView.reloadData()
}
}
}
func filterContent(for searchText: String) {
searchResults = item.filter({ (item) -> Bool in
if let model = item.model {
let isMatch = model.localizedStandardContains(searchText)
return isMatch
}
return false
})
}
}请给我建议。
加伦,向你问好
发布于 2020-06-20 05:32:57
将obscuresBackgroundDuringPresentation更改为false。
对于我的情况,我使用dimsBackgroundDuringPresentation。这是不可取的。
由于我使用的是相同的ViewController,因此上述设置必须设置为false。
https://stackoverflow.com/questions/62393600
复制相似问题