带自定义类的SearchBar

时间:2017-08-02 12:19:45

标签: ios uitableview uisearchbar

我是iOS开发的初学者,当我尝试在collectionView.isUserInteractionEnabled = true中使用UISearchBar时出现问题。 我不知道如何在表视图中使用自定义类,该视图使用搜索栏过滤数据。拜托,你能解决这个问题吗?以下是自定义类:

UITableView

ViewController.swift

//  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
}}

2 个答案:

答案 0 :(得分:0)

    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()


            }
        }

答案 1 :(得分:0)

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()
}

使用上述方法。