需要你的帮助,我正在使用Table View,我有一个从服务器收到的数组。数组只是多项选择选项。它看起来像这样
一个。表
湾瓶子
℃。帽子
d。桶
即以上都不是。
我想要什么? 我想选择多个答案,例如桌子,瓶子,水桶,它会显示复选框。我设法做得很好。当选择最后一个选项,即上面的选项时,我想取消选择所有上面选中的标记选项,只显示选中的无选项,即使这样也有效。
我被困在哪里? 当"以上都不是"处于选定模式,我点击任何其他选项然后"无"应该取消选择。这不起作用,我不知道这里有什么不对。请帮忙。 TIA
这是我的didSelect方法
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if selectedString == "None of the above" {
selectedIndex = indexPath.row
self.isNoneSelected = true
for index in tableView.indexPathsForSelectedRows!
{
tableView.deselectRowAtIndexPath(index, animated: true)
}
}
我的无选项将始终位于最后位置,所以即使是array.lastobject也能正常工作
答案 0 :(得分:0)
好的,我无法确定,但看起来此代码处理所有选择事件,对吧?如果是这样,似乎有几个问题:
1)selectedIndex
仅在选择最后一项时设置。我怀疑这不是你想要的,但我不能确定。
2)同样适用于self.isNoneSelected = true
- 我怀疑你想在其他方法中使用此值来查看是否是所选项目,但您似乎没有任何代码可以再次将其关闭
3)您关闭所有其他项目的选择,但不打开选择" none" - 但事件中可能已经发生过,我在那里看不到剩下的代码。
所以我认为你想要这样的东西:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndex = indexPath.row
if selectedString == "None of the above" {
self.isNoneSelected = true
for index in tableView.indexPathsForSelectedRows!
{
tableView.deselectRowAtIndexPath(index, animated: true)
}
} else {
self.isNoneSelected = false
//NOTE I AM NOT AT MY MACHINE SO I DON'T KNOW THE EXACT SYNTAX HERE
//THE IDEA IS TO GET THE INDEX PATH OF THE LAST ITEM SO WE CAN TURN IT OFF
tableView.deselectRowAtIndexPath(NSIndexPath.indexPathForRow(mydatasource.count-1, inSection:0), animated: true)
}
}
答案 1 :(得分:0)
你这里太复杂了。如果添加UIImageView来表示选定状态,您只需要一个用于存储所选状态的布尔数组,以及用于tableView的 reloadData()。 直接为每一行调用tableView.deselectRow()不是一个好主意
var selected = Array(repeating: false, count: 5)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) {
//let cell = whatever
cell.checkMark.isHidden = !selected[indexPath.row]
//return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
selected[indexPath.row] = !selected[indexPath.row]
if (indexPath.row == selected.count - 1 ) {//if 'None' is selected
for i in 0..<selected.count-2 {
selected[i] = false
}
} else { //all other rows will deselect the 'None' row
selected[selected.count - 1 ] = false
}
tableView.reloadData()
}