Ios 点击一行时,将UITableViewCell复选标记添加到多行
我有一个表格视图,不是所有的单元格都可以同时看到。我试图使它,以便当一行是轻触它添加了一个复选标记附件的细胞。我的问题是它也会将其添加到其他行中。在我的表格视图中,有4行完全显示,第五行几乎没有显示。如果我选中第一个框,它将在每第五个框中添加一个复选标记(例如indexPath.row=0,5,10,15…),尽管indexPath.row不同Ios 点击一行时,将UITableViewCell复选标记添加到多行,ios,swift,uitableview,Ios,Swift,Uitableview,我有一个表格视图,不是所有的单元格都可以同时看到。我试图使它,以便当一行是轻触它添加了一个复选标记附件的细胞。我的问题是它也会将其添加到其他行中。在我的表格视图中,有4行完全显示,第五行几乎没有显示。如果我选中第一个框,它将在每第五个框中添加一个复选标记(例如indexPath.row=0,5,10,15…),尽管indexPath.row不同 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIn
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: DropDownMenuCell = tableView.dequeueReusableCellWithIdentifier("DropDownMenuCell", forIndexPath: indexPath) as! DropDownMenuCell
cell.dropDownCellLabel?.text = DropDownItems[indexPath.row].Name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell: DropDownMenuCell = tableView.cellForRowAtIndexPath(indexPath) as! DropDownMenuCell
print(indexPath.row)
if selectedCell.accessoryType == .None {
selectedCell.accessoryType = .Checkmark
} else {
selectedCell.accessoryType = .None
}
}
编辑:抱歉重复,我最初搜索这个问题时没有显示其他问题。我已经在swift中得到了一个有效的答案,或者我会尝试通过objective c post来解决我的问题。在数据源中维护要选择的单元格 然后在cellForRowAtIndexPath中:
if (DropDownItems[indexPath.row].isSelected) {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
在didSelectRowAtIndexPath方法中:
if(DropDownItems[indexPath.row].isSelected) {
DropDownItems[indexPath.row].isSelected = false
} else {
DropDownItems[indexPath.row].isSelected = true
}
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
在Swift 3中,这应有助于:
import UIKit
class ViewController: UITableViewController {
let foods = ["apple", "orange", "banana", "spinach", "grape"]
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return foods.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = foods[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark
{
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
}
else
{
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
可能重复使用Tableview单元格。您需要维护已点击单元格的索引数组,并根据数组在
tableView:cellforrowatinexpath:
中设置复选标记。如果您搜索StackOverflow,您将发现其他有关单元格重复使用的问题。