【发布时间】:2017-08-04 01:19:29
【问题描述】:
目前,我有一个 tableview 设置子类化 tableviewcell。在这个 tableviewcell 上,我有一个显示添加或显示的按钮。我想知道是否有办法存储按钮相对于其行的状态。例如,我有一个搜索栏和这个表格视图,如果我将表格视图第 4 行的按钮状态更改为从添加中减去,然后在搜索栏中搜索特定行,它将显示在第一行,但不会保留按钮的状态。我想知道是否有办法在不使用后端(或数据库)的情况下做到这一点。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = data.filter({ (text) -> Bool in
let tmp: NSString = text as NSString
let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if (filtered.count == 0){
searchActive = false
} else {
searchActive = true
}
self.TableView.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Hello")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchActive == true {
return filtered.count
}
return data.count
}
var status = [IndexPath: Bool]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ListCell
cell.cellDelegate = self
cell.contentView.bringSubview(toFront: cell.Button)
if status[indexPath] ?? false {
cell.Button.setTitle("Subtract", for: .normal)
} else {
cell.Button.setTitle("Add", for: .normal)
}
cell.indexPath = indexPath
if(searchActive) {
cell.textLabel?.text = filtered[indexPath.row]
} else {
cell.textLabel?.text = data[indexPath.row]
}
cell.contentView.bringSubview(toFront: cell.Button)
return cell
}
func didPressButton(indexPath: IndexPath) {
guard let cell = TableView.cellForRow(at: indexPath) as? ListCell else {
return
}
if status[indexPath] ?? false {
status[indexPath] = false
cell.Button.setTitle("Add", for: .normal)
} else {
status[indexPath] = true
cell.Button.setTitle("Subtract", for: .normal)
}
}
【问题讨论】:
-
您似乎有跟踪状态的代码;发生了什么或不起作用?
-
嗯,是的,如果我单击该按钮,它将更改状态,例如从添加 -> 减去,我可以通过再次单击将其恢复为添加。我感兴趣的是当我将任何行设置为减去,然后使用我的搜索栏搜索它时,按钮状态将不会持续存在,因为它采用第一行的按钮状态(或前几个,无论它过滤多少) .我想知道如何让按钮状态与数据一起过滤。
-
您的问题是您的
status数组的索引与data数组的索引相同,因此当您使用filtered数组时,status值不会映射。您可以将[String:Bool]的字典用于您的status值,其中键是data数组中的相关值。那么status将独立于索引 -
前段时间我也遇到过类似的问题,当我使用
currentTitle时它工作正常。你能试试吗? -
正如其他人所说,indexPath会在不同的搜索之间发生变化,因此无法使用。您显示的数据是否具有某种形式的唯一键?如果是这样,
status应该是该键的字典,然后您可以在cellForRowAt中查找。
标签: ios swift uitableview button