【发布时间】:2017-02-05 21:40:50
【问题描述】:
我必须使用搜索栏在 tableview 中执行搜索操作。
其中有一个人的姓名标签和这些人在其单元格中的图像。
我的代码是
override func viewDidLoad() {
super.viewDidLoad()
ArrPersons = ["Mahatma Gandhi","Pramukh Swami","Akshay Kumar","Sachin Tendulkar","Chetan Bhagat","Sardar Vallabhai Patel","Amitabh Bachchan"]
arrPersonImages = ["1.png","2.png","3.png","4.png","5.png","6.png","7.png"]
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if (searchText.characters.count>0) {
let predicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchText)
ArrPersons = arrTemp
let array = (self.ArrPersons as NSArray).filteredArrayUsingPredicate(predicate)
print(array)
ArrPersons = array as! [String]
}
else
{
ArrPersons = arrTemp
}
self.tableviewww.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.ArrPersons.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableviewww.dequeueReusableCellWithIdentifier("mycell")as! buildVcCell
cell.personsImages.image = UIImage (named:arrPersonImages[indexPath.row] )
cell.labelPersonNamess?.text = self.ArrPersons[indexPath.row]
cell.addBtn.addTarget(self, action: #selector(BuildVc.AddbuttonClicked(_:)), forControlEvents: .TouchUpInside)
return cell
}
问题是这段代码只对标签persons数组执行搜索。 arrPersonImages 没有根据在搜索栏中输入的人的姓名进行过滤。
【问题讨论】:
-
你没有在搜索textdidchange函数中对
arrPersonImages进行过滤,所以所有的图像都还在。我认为您最好创建一个字典来保留人名和图像,例如[[name: "Michael", image: "1.png"], [name: "Peter", image: "2.png"], ...],然后您只需为该数组过滤一次 -
感谢@Enix 的建议..我试图像这样更改我的代码,但它不起作用..
-
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if (searchText.characters.count>0) { let predicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchText ) arrayyPersonsNImages = arrTemp let array = (self.arrayyPersonsNImages as NSMutableArray).filteredArrayUsingPredicate(predicate) print(array) arrayyPersonsNImages = array as AnyObject 一样! NSMutableArray } else { arrayyPersonsNImages = arrTemp } self.tableVieww.reloadData()
-
您不能使用先前定义的
predicate过滤arrayyPersonsNImages 数组,因为您的谓词是通过过滤人名定义的。您的图像名称不包含任何人名,对吗?
标签: ios swift iphone uitableview