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

Swift 3中如何在UISearchBar内按id字段过滤数组模型

基于模型ID字段过滤数组的Swift实现方案

我来帮你搞定这个基于id字段过滤数组的需求,结合你已经写的代码,咱们一步步补全功能:

第一步:确认核心数据源

首先你需要一个原始数据源数组(用来存放所有未过滤的模型数据),和你已有的filteredData区分开,比如:

// 原始数据源,存放所有Assess_order_med_model实例
var originalData: [Assess_order_med_model] = []
// 你已经定义的过滤后数据
var filteredData = [Assess_order_med_model]()

第二步:补全viewDidLoad初始化逻辑

在viewDidLoad里初始化原始数据,同时让表格默认显示全部内容:

override func viewDidLoad() { 
    super.viewDidLoad() 
    table_View.dataSource = self 
    table_View.delegate = self 
    searchBar.delegate = self 
    searchBar.showsCancelButton = false 
    self.table_View.allowsSelection = false // 补全你没写完的false
    
    // 示例:替换成你的真实数据源初始化逻辑
    originalData = [
        Assess_order_med_model(name: "药品甲", id: "MED001"),
        Assess_order_med_model(name: "药品乙", id: "MED002"),
        Assess_order_med_model(name: "药品丙", id: "MED010"),
        Assess_order_med_model(name: "药品丁", id: "MED011")
    ]
    
    // 初始状态显示全部数据
    filteredData = originalData
    table_View.reloadData()
}

第三步:实现搜索栏的过滤逻辑

通过UISearchBarDelegate的方法监听搜索输入,利用Swift的filter高阶函数完成基于id的过滤:

// MARK: - UISearchBarDelegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    // 处理搜索框为空/仅输入空格的情况:恢复显示全部数据
    guard !searchText.trimmingCharacters(in: .whitespaces).isEmpty else {
        filteredData = originalData
        table_View.reloadData()
        return
    }
    
    // 执行过滤:匹配模型的id字段
    filteredData = originalData.filter { model in
        // 可选:忽略大小写,提升搜索体验;如果需要精确匹配,改成 == 即可
        model.id.lowercased().contains(searchText.lowercased())
    }
    
    // 刷新表格展示过滤结果
    table_View.reloadData()
}

// 可选:点击搜索按钮收起键盘
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
}

关键细节说明

  • 过滤逻辑灵活调整:如果需要精确匹配ID(比如输入"MED001"才显示对应模型),把contains改成==即可:
    model.id == searchText
    
  • 空输入处理:加入了trimmingCharacters避免用户输入空格导致的异常
  • 大小写兼容:.lowercased()让搜索不区分大小写,符合大部分用户的使用习惯

最后别忘了确保你的UITableViewDataSource方法是基于filteredData来返回数据的,比如:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath)
    let model = filteredData[indexPath.row]
    cell.textLabel?.text = model.name
    cell.detailTextLabel?.text = model.id
    return cell
}

内容的提问来源于stack exchange,提问作者asif saifi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:26:58