2016-11-04 66 views
0

我有陣如何UISearchcontroller customcell迅速

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

,並實現代碼如下顯示的數據

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

我想搜索名稱tableview中會顯示姓名和薪水如何使用它感謝

+0

請檢查http://stackoverflow.com/a/24387424/2594560 –

+0

啊得到它謝謝 –

回答

1

您的數組轉換字典:

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刪除方法:

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的刪除方法:

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 
}