具有自定义类的搜索栏

Posted

技术标签:

【中文标题】具有自定义类的搜索栏【英文标题】:SearchBar with Custom Class 【发布时间】:2017-08-02 12:19:45 【问题描述】:

我是 ios 开发的初学者,当我尝试在 UITableView 中使用 UISearchBar 时遇到问题。 我不知道如何在使用搜索栏过滤数据的表格视图中使用自定义类。请问,你会解决这个问题吗?下面是自定义类:

//  Data.swift
//  SearchBarWithTableView

class Food 
var FoodName:String = ""
var FoodQuantity:String = ""
var FoodGroup:String = ""
var FoodImage:String = ""
var FoodCarbs:Int = 0
var FoodCalories:Int = 0

init(foodName:String,foodGroup:String,foodQuantity:String,foodImage:String,foodCarbs:Int,foodCalories:Int) 
    self.FoodName = foodName
    self.FoodQuantity = foodQuantity
    self.FoodGroup = foodGroup
    self.FoodImage = foodImage
    self.FoodCarbs = foodCarbs
    self.FoodCalories = foodCalories

ViewController.swift

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate

    @IBOutlet weak var SearchBarTableView:UITableView!
    @IBOutlet weak var SearchBar:UISearchBar!




    var searchActive:Bool=false
    var filteredData=[Food]()

    let allData:[Food]=[Food(foodName: "Rice", foodGroup: "Beans", foodQuantity: "5 scope",foodImage:"1S.jpg", foodCarbs:15,foodCalories: 80),
                        Food(foodName: "Apple", foodGroup: "Frutie", foodQuantity: "One",foodImage:"S-2.jpg", foodCarbs: 15, foodCalories: 80),
                        Food(foodName: "ban 1",foodGroup: "Beans",foodQuantity:"One",foodImage:"3S.jpg",foodCarbs: 15,foodCalories: 80),
                        Food(foodName: "ban 2", foodGroup: "Beans", foodQuantity: "half pieace",foodImage:"4-S.jpg", foodCarbs: 25, foodCalories: 140)]



    override func viewDidLoad() 

        super.viewDidLoad()

        SearchBarTableView.delegate=self
        SearchBarTableView.dataSource=self
        SearchBar.delegate=self
        filteredData=allData
        print(filteredData.count)
        print("-----------")
        print(allData.count)
        SearchBar.returnKeyType=UIReturnKeyType.done
        definesPresentationContext=true
    
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
            let cell=tableView.dequeueReusableCell(withIdentifier: "cell")
                var Text:String
                if searchActive 
                    Text=filteredData[indexPath.row].FoodName
                else
                    Text=allData[indexPath.row].FoodName
                
                cell?.textLabel?.text=filteredData[indexPath.row].FoodName
                return cell!
            

        func searchBar(_ searchBar: UISearchBar, textDidChange `searchText: String) `
            if SearchBar.text == nil || SearchBar.text == "" 
                searchActive=false
                view.endEditing(true)
                SearchBarTableView.reloadData()
            else
                searchActive=true
    /* here is the problem */
                 //   filteredData=allData.filter($0 === searchBar.text!) 
                
            
        func numberOfSections(in tableView: UITableView) -> Int 
            return 1
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

            if searchActive 
                return filteredData.count
            
            return allData.count
        

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
           if segue.identifier=="Go"
            if let indexPath=SearchBarTableView.indexPathForSelectedRow
                let destinationVC=segue.destination as! DetailsViewController
                destinationVC.namE=allData[indexPath.row].FoodName
                destinationVC.quntitY=allData[indexPath.row].FoodQuantity
                destinationVC.calorieS=allData[indexPath.row].FoodCalories
                destinationVC.carbS=allData[indexPath.row].FoodCarbs
            
        
      
    

【问题讨论】:

【参考方案1】:
    func searchBar(_ searchBar: UISearchBar, textDidChange `searchText: String) `
        if SearchBar.text == nil || SearchBar.text == "" 
            searchActive=false
            view.endEditing(true)
            SearchBarTableView.reloadData()
        else
            searchActive=true

                filteredData=allData.filter($0.FoodName === searchBar.text!) 
            SearchBarTableView.reloadData()


            
        

【讨论】:

【参考方案2】:
func updateSearchResults(for searchController: UISearchController) 
    if let searchText = searchController.searchBar.text, !searchText.isEmpty 
        self.filteredData = self.allData.filter
            var found = false
            for str in ($0 as! NSDictionary) 
                if(str.key as! String == "foodName")
                
                    var strin = str.value as! String;
                    strin = strin.lowercased();
                    let search = searchText.lowercased()
                    found = strin.contains(search);
                                    
            
            return found
        
    
    else 
        self.Array = response as! [Any]
    
    tableView.reloadData()

使用上述方法。

【讨论】:

以上是关于具有自定义类的搜索栏的主要内容,如果未能解决你的问题,请参考以下文章

如何减少iOS导航栏自定义视图的左右间隙

具有自定义类的原型单元不会触发初始化?

状态栏自定义文本颜色

ActionBarSherlock - 带有分隔线的操作栏自定义背景

iOS 11导航栏自定义后退按钮问题

iOS NavigationBar 导航栏自定义