我的搜索栏有问题。我试着用搜索栏在一个表视图中搜索,但是当我键入什么东西时,它什么也没有显示,在我删除所有试图搜索的餐馆之后,所有的餐馆都消失了。
这是我正在使用的代码。我只张贴必要的东西
extension HomeViewController: UISearchBarDelegate{
//MARK: Search bar
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = []
if searchText == "" {
filteredData = datas
}
else {
for restaurante in datas{
if restaurante.title.lowercased().contains(searchText.lowercased())
{
filteredData.append(restaurante)
}
}
}
self.homeTableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // Dispare tastatura cand apasam pe search
searchBar.resignFirstResponder()
}
}这是变量:
struct Category {
let title: String
let photoKeyHome: String
}
let datas: [Category] = []
var filteredData: [Category]!
override func viewDidLoad() {
super.viewDidLoad()
filteredData = datas
}这是我的桌景。也许我在这里做错了什么。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = homeTableView.dequeueReusableCell(withIdentifier: "homeTableViewCell", for: indexPath) as! homeTableViewCell
let restaurant = filteredData[indexPath.row]
let storageRef = Storage.storage().reference()
let photoRef = storageRef.child(restaurant.photoKeyHome)
cell.myLabel.text = restaurant.title
cell.myImage.sd_setImage(with: photoRef)对于数据,im使用Firestore和firebase存储。这就是我如何从Firestore中获取数据的方式。
func getDatabaseRecords() {
let db = Firestore.firestore()
// Empty the array
filteredData = []
db.collection("HomeTableViewRestuarants").getDocuments { (snapshot, error) in
if let error = error {
print(error)
return
} else {
for document in snapshot!.documents {
let data = document.data()
let newEntry = Category(
title: data["title"] as! String,
photoKeyHome: data["photoKeyHome"] as! String
)
self.filteredData
.append(newEntry)
}
}
DispatchQueue.main.async {
self.homeTableView.reloadData()
}
}
}发布于 2021-04-10 20:18:13
正如注释中提到的,datas从未被设置过。在getDatabaseRecords替换中
DispatchQueue.main.async {
self.homeTableView.reloadData()
}使用
DispatchQueue.main.async {
self.datas = self.filteredData
self.homeTableView.reloadData()
}顺便说一句,您的textDidChange方法效率很低。代之以
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filteredData = datas
} else {
filteredData = datas.filter{ $0.title.range(of: searchText, options: .caseInsensitive) != nil }
}
self.homeTableView.reloadData()
}https://stackoverflow.com/questions/67038634
复制相似问题