2017-10-17 83 views
0

UITableViewcheckmark发生的是取消选择当我滚动UITableView的滚动型与取消的问题

代码

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell") 
    cell.textLabel?.text=dizi[indexPath.row] 

    return cell 
} 

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 
    } 
} 

first

second

我怎样才能解决这个问题?请帮帮我。

回答

0

那是因为在UITableView的细胞,当你滚动并得到重用,是你的责任,以确保它恢复其UI状态重用

时因此,创建一个数组来保存所选indexPath

var selectedIndex : [IndexPath]! = [IndexPath]() 

cellForRowAtIndexPath

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell") 
    if if selectedIndex.contains(indexPath) { 
     cell.accessoryType = UITableViewCellAccessoryType.checkmark 
    } 
    else { 
     cell.accessoryType = UITableViewCellAccessoryType.none 
    } 
    cell.textLabel?.text=dizi[indexPath.row] 

    return cell 
} 

最后更新selectedIndexArray

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{ 
    if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark 
    { 
     tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none 
     self.selectedIndex = selectedIndex.filter({ 
      return $0 != indexPath 
     }) 
    } 
    else 
    { 
     tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark 
     self.selectedIndex.append(indexPath) 
    } 

} 
+0

非常感谢你解决 – Tiskender2

+0

@ tiskender2:随时欢迎好友:)我很高兴我能有帮助:)快乐的编码 –

0

因为您还需要在cellForRowAt中设置UITableViewCellAccessoryType。因为如果使用向上/向下滚动表格,那么单元格将被重用。

怎么办?走行的一个阵列相同的大小和值0重复,当你做检查的任何行,然后用indexPath.row更新值1,如果你取消任何行,然后用indexPath.row

cellForRowAt方法之前return cell放条件像更新值0

if checkUncheckArr[indexPath.row] == 0 { 
     tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.non 

} 
else { 
     tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark 

} 
+0

感谢您的回答 – Tiskender2