2016-07-29 48 views
0

我在我的UITableView中有多个部分,每个部分都有不同数量的UITableViewCells如何跟踪使用NSIndexPath选择的单元格?

我想跟踪为每个部分选择的单元格,并显示已选择单元格的图像。

所以我想在阵列中存储它们:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    someArray.append(indexPath) 
} 

,然后显示已被选定为单元的图像:

for indices in self.someArray { 
    if indices == indexPath { 
     cell.button.setImage(UIImage(named: "selected"), forState: UIControlState.Normal) 
    } else { 
     cell.button.setImage(UIImage(named: "unselected"), forState: UIControlState.Normal) 
    } 
} 

我还想让它如此每个部分只能选择一个单元格,并且每个部分的每个选择部分都会保留。

选择只是不应该保持原样。每次我在某一行的0节中进行选择时,它都会为其他节选择相同的行索引。

我该如何解决这个问题?

回答

3

我建议为您的视图控制器维护一个数据模型,该视图控制器将保留您各个部分中每个单元的所有选定状态。 (选择一个更贴切的名称来描述您的单元格项目)。

struct Element { 
    var isSelected: Bool // selection state 
} 

然后您的视图控制器将有一个数据模型,像这样:

var dataModel: [[Element]] // First array level is per section, and second array level is all the elements in a section (e.g. dataModel[0][4] is the fifth element in the first section) 

此数组可能会被初始化为一堆元素组成,其中isSelected是假的,假设你开始取消所有行。现在

tableView:didSelectRowAtIndexPath功能会是这个样子:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    // Check if there are any other cells selected... if so, mark them as deselected in favour of this newly-selected cell 
    dataModel[indexPath.section] = dataModel[indexPath.section].map({$0.isSelected = false}) // Go through each element and make sure that isSelected is false 

    // Now set the currently selected row for this section to be selected 
    dataModel[indexPath.section][indexPath.row].isSelected = true 
    } 

(一种更有效的方式可能是让每个部分选择的最后一行,并标注虚假的,而不是映射整个子阵列)

现在,在tableView:cellForRowAtIndexPath中,您必须显示是否根据您的dataModel选择了单元格。如果您没有在数据模型中维护您的选定状态,只要单元格滚动屏幕,它将失去其选定状态。此外,dequeueReusableCellWithIdentifier将重用可能反映您所选状态的单元格,如果您没有正确刷新您的单元格。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("yourCellIdentifier") as! YourCellType 

    // If your data model says this cell should be selected, show the selected image 
    if dataModel[indexPath.section][indexPath.row].isSelected { 
     cell.button.setImage(UIImage(named: "selected"), forState: UIControlState.Normal) 
    } else { 
     cell.button.setImage(UIImage(named: "unselected"), forState: UIControlState.Normal) 
    } 
    } 

希望有道理!

+0

有道理。所以它xcode不喜欢这行:dataModel [indexPath.section] = dataModel [indexPath.section] .map({$ 0.isSelected = false}) –

+0

此外,我得到:致命错误:索引超出范围如果dataModel [indexPath.section] [indexPath.row] .isSelected { –

+0

对不起,我没有尝试自己运行代码!你可以用一个for循环替换地图,通过子数组中的每个元素,并确保它被取消选择。至于索引超出范围,也许你需要实现tableView:numberOfSectionsInTableView来返回正确数量的节,类似于tableView:numberOfRowsInSection。两者都应该返回基于你的dataModel的.count属性的值,这样你不应该得到一个索引超出范围... – Undrea