2016-07-29 49 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