我创建了一个包含Firebase数据的表视图。现在,我想添加一个搜索栏,以按storeName
过滤数据。
这是我当前的Table View Controller的外观:
我的数据库如下:
我的数据模型(StoreModel):
class StoreModel{
var name: String?
var desc: String?
var url: String?
var rate: Double
init(
name: String?, desc: String?, url: String?, rate: Double){
self.name = name
self.desc = desc
self.url = url
self.rate = rate
}
我如何从Firebase获取数据:
var storeList = [StoreModel]()
var refStores: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
FirebaseApp.configure()
refStores = Database.database().reference().child("stores")
refStores.observe(DataEventType.value, with: {(snapshot) in
if snapshot.childrenCount > 0{
self.storeList.removeAll()
for stores in snapshot.children.allObjects as! [DataSnapshot]{
let storeObject = stores.value as? [String: AnyObject]
let storeName = storeObject?["storeName"]
let storeDesc = storeObject?["storeDesc"]
let storeUrl = storeObject?["storeUrl"]
let storeRate = storeObject?["storeRate"]
let store = StoreModel(
name: storeName as! String?, desc: storeDesc as! String?, url: storeUrl as! String?, rate: storeRate as! Double)
self.storeList.append(store)
}
self.tblSearch.reloadData()
}
})
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ViewControllerTableViewCell
let store: StoreModel
store = storeList[indexPath.row]
cell.labelName.text = store.name
cell.labelDesc.text = store.desc
cell.imageStore.setImage(from: store.url)
cell.imageStore.clipsToBounds = true
cell.imageStore.layer.cornerRadius = 20
cell.imageGrey.clipsToBounds = true
cell.imageGrey.layer.cornerRadius = 20
cell.cosmosView.rating = store.rate
return cell
}
感谢您的帮助!
答案 0 :(得分:1)
尝试以下操作。
import UIKit
import FirebaseDatabase
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Variables
var refStores: DatabaseReference!
func runSearch(key: String) {
_ = refStores.queryOrdered(byChild: "storeName").queryEqual(toValue: key).observeSingleEvent(of: .value, with: { (dataSnapshot) in
if dataSnapshot.childrenCount > 0 {
for store in dataSnapshot.children.allObjects as! [DataSnapshot] {
let key = store.key
let object = store.value as! [String: Any]
let storeDesc = object["storeDesc"] as! String
let storeUrl = object["storeUrl"] as! String
let storeRate = object["storeRate"] as! Int
let storeModel = StoreModel(...
self.storeList.append(storeModel)
}
}
self.tableView.reloadData()
}, withCancel: {(Err) in
print(Err.localizedDescription)
})
}