You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Swift结合Firebase Database实现UISearchBar功能的代码咨询

看来你已经搭好了基础的UI和变量框架,不过还缺几个关键部分——比如和Firebase的数据联动、完整的搜索过滤逻辑,还有TableView数据源的适配。我帮你把这些补全并优化:

第一步:修正变量与基础配置

先调整变量类型让它和数据模型匹配,同时确保ViewController遵守必要的代理协议:

import UIKit
import FirebaseDatabase

class HospitalListViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableViewhospitalss: UITableView! 
    @IBOutlet weak var searchBar: UISearchBar! 
    
    // 存储所有医院的完整列表
    var hospitalsList = [hospitalsModel]() 
    var searchActive : Bool = false 
    // 修正类型:和hospitalsList保持一致,存储筛选后的医院模型
    var filteredHospitals: [hospitalsModel] = [] 

    override func viewDidLoad() {
        super.viewDidLoad()
        // 绑定代理
        searchBar.delegate = self
        tableViewhospitalss.dataSource = self
        tableViewhospitalss.delegate = self
        // 从Firebase拉取初始数据
        fetchHospitalsFromFirebase()
        // 给搜索栏添加取消按钮
        searchBar.showsCancelButton = true
    }
}

第二步:实现Firebase数据获取逻辑

添加从Firebase Database拉取医院数据的方法,把数据存入hospitalsList并刷新表格:

extension HospitalListViewController {
    func fetchHospitalsFromFirebase() {
        // 替换成你Firebase中存储医院数据的节点路径
        let hospitalRef = Database.database().reference().child("hospitals")
        
        // 监听数据变化(实时更新)
        hospitalRef.observe(.value) { snapshot in
            self.hospitalsList.removeAll()
            
            // 遍历Firebase返回的快照数据
            for childSnapshot in snapshot.children {
                guard let snapshot = childSnapshot as? DataSnapshot,
                      let hospitalData = snapshot.value as? [String: Any],
                      // 这里根据你的hospitalsModel属性调整字段
                      let hospitalName = hospitalData["name"] as? String,
                      let hospitalAddress = hospitalData["address"] as? String else {
                    continue
                }
                
                let hospital = hospitalsModel(name: hospitalName, address: hospitalAddress)
                self.hospitalsList.append(hospital)
            }
            
            // 数据加载完成后刷新表格
            self.tableViewhospitalss.reloadData()
        }
    }
}

第三步:补全UISearchBar代理方法

把你没写完的搜索逻辑补全,实现实时筛选:

extension HospitalListViewController {
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchActive = true
        tableViewhospitalss.reloadData()
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchActive = false
        searchBar.text = ""
        tableViewhospitalss.reloadData()
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchActive = false
        searchBar.text = ""
        searchBar.resignFirstResponder()
        tableViewhospitalss.reloadData()
    }
    
    // 实时搜索:用户输入时自动筛选
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        // 按医院名称模糊匹配(忽略大小写),你可以改成按地址或其他字段筛选
        filteredHospitals = hospitalsList.filter { hospital in
            return hospital.name.lowercased().contains(searchText.lowercased())
        }
        
        searchActive = !searchText.isEmpty
        tableViewhospitalss.reloadData()
    }
    
    // 点击搜索按钮收起键盘
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
}

第四步:适配UITableView数据源

让表格根据搜索状态显示对应的数据:

extension HospitalListViewController {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 根据搜索状态返回对应数据的数量
        return searchActive ? filteredHospitals.count : hospitalsList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 替换成你的Cell标识符和自定义Cell类
        let cell = tableView.dequeueReusableCell(withIdentifier: "HospitalCell", for: indexPath) as! HospitalTableViewCell
        
        // 根据搜索状态获取当前行的医院数据
        let currentHospital = searchActive ? filteredHospitals[indexPath.row] : hospitalsList[indexPath.row]
        
        // 给Cell赋值
        cell.hospitalNameLabel.text = currentHospital.name
        cell.hospitalAddressLabel.text = currentHospital.address
        
        return cell
    }
}

额外提示

  • 确保你的hospitalsModel有对应的初始化方法和属性(比如name、address),如果需要其他字段,在Firebase数据解析和Cell赋值部分对应调整。
  • 记得给TableView设置正确的Cell标识符,并且自定义Cell类要和代码中的HospitalTableViewCell匹配。
  • 如果Firebase的数据结构不同,要修改fetchHospitalsFromFirebase里的字段解析逻辑,保证和你的数据库结构一致。

内容的提问来源于stack exchange,提问作者hamada raouf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:42:37