Yasuhiro Kondo
Yasuhiro Kondo

Reputation: 197

How to UISearchcontroller customcell swift

I have Array

let Name:[String] = ["John","Peter","Jack"]
let Sal:[String] = ["50000","37000","63000"]

and tableview to show data

{
    Name:John
    Salary:50000
}
{
    Name:Peter
    Salary:37000
}
{
    Name:Jack
    Salary:63000
}

I want to Search name tableview will display Name and Salary how to use it thanks

Upvotes: 0

Views: 80

Answers (1)

Jayesh Miruliya
Jayesh Miruliya

Reputation: 3317

Your array convert dictionry:

let Name:[String] = ["John","Peter","Jack"]
let Sal:[String] = ["50000","37000","63000"]

var AllData:Array<Dictionary<String,String>> = []
var SearchData:Array<Dictionary<String,String>> = []

for i in 0..<Name.count
{
    var data:Dictionary<String, String> = Dictionary<String, String>()
    data["name"] = Name[i]
    data["salary"] = Sal[i]
    AllData.insert(data, at: AllData.count)
}

SearchData=AllData

UISearchBar Delete Method :

func searchBar(searchBar: UISearchBar, textDidChange searchText: String)
{
    let predicate=NSPredicate(format: "name CONTAINS[cd] %@", searchText)
    let arr=(AllData as NSArray).filtered(using: predicate)

    if arr.count > 0
    {
        SearchData.removeAll(keepingCapacity: true)
        SearchData=arr as! Array<Dictionary<String, String>>
    }
    else
    {
        SearchData=AllData
    }
    tableview.reloadData()
}

func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
    self.searchBar.resignFirstResponder()
}

UITableView Delete Method:

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

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return 44
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell

    var Data:Dictionary<String,String> = SearchData[indexPath.row]
    cell.NameLbl.text = Data["name"]
    cell.SalaryLbl.text = Data["salary"]

    return cell
}

Upvotes: 1

Related Questions