我建議爲您的視圖控制器維護一個數據模型,該視圖控制器將保留您各個部分中每個單元的所有選定狀態。 (選擇一個更貼切的名稱來描述您的單元格項目)。
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)
}
}
希望有道理!
有道理。所以它xcode不喜歡這行:dataModel [indexPath.section] = dataModel [indexPath.section] .map({$ 0.isSelected = false}) –
此外,我得到:致命錯誤:索引超出範圍如果dataModel [indexPath.section] [indexPath.row] .isSelected { –
對不起,我沒有嘗試自己運行代碼!你可以用一個for循環替換地圖,通過子數組中的每個元素,並確保它被取消選擇。至於索引超出範圍,也許你需要實現tableView:numberOfSectionsInTableView來返回正確數量的節,類似於tableView:numberOfRowsInSection。兩者都應該返回基於你的dataModel的.count屬性的值,這樣你不應該得到一個索引超出範圍... – Undrea