2017-06-19 66 views
1

我在我的tableViewCell中有一個imageView,我希望在選擇時更改它的圖像。這是我有它的代碼:在UITableViewCell中選擇圖像(Swift 3 xcode)

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let myCell = tableView.cellForRow(at: indexPath) as! TableCell 
    myCell.resourceIcons.image = UIImage(named: "RubiusResources2") 
    tableView.deselectRow(at: indexPath, animated: true) 

} 

代碼工作,但在不同的部分再往下的tableView還有些其他行似乎變化。

編輯:

使用意見婁我來到了以下解決方案:

我首先創建一個2D布爾陣列部分和行我的表已經和他們都設置爲false量。

var resourceBool = Array(repeating: Array(repeating:false, count:4), count:12) 

然後我創建了一個if語句來檢查indexPath中的數組是否爲false或true。這將是圖像狀態改變的地方。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let myCell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! TableCell 

    if (global.resourceBool[indexPath.section][indexPath.row] == false) { 
     myCell.resourceIcons.image = global.systemResourceImages[0] 
    } else if (global.resourceBool[indexPath.section][indexPath.row] == true) { 
     myCell.resourceIcons.image = global.systemResourceImages[1] 
    } 

    return myCell 
} 

然後,在didSelectRow函數中,我將indexPath處的數組更改爲true,並重新載入tableView數據。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    global.resourceBool[indexPath.section][indexPath.row] = true 
    tableView.reloadData() 
    tableView.deselectRow(at: indexPath, animated: true) 

} 

根據我的理解,對象的狀態必須始終位於cellForRow中。

+0

看到我的評論:https://stackoverflow.com/questions/44618366/swift-uicollectionview-cells-arent-停止訂購#comment76222954_44618366這對桌面瀏覽來說是一回事,單元格正在被重用,單元格不能保持狀態,圖像變化是狀態。 – luk2302

+1

有一個單元重用。您需要始終在單元格的prepareForReuse上設置原始背景。基本上,在prepareForReuse上,您應該將單元格中的所有屬性設置爲原始狀態。 – teixeiras

+0

@ luk2302是正確的,這是一個很好的解決方案,但如果您對所有單元格的選定狀態使用相同的圖像,則將該圖像置於imageView突出顯示的狀態並僅更改所選行行的狀態。 並在.image屬性中使用正常圖像。 –

回答

2

其中一個解決方案是您需要維護您選擇的行的單獨列表,並在cellForRowAt方法中比較它們。

代碼看起來像這樣。

var selectedArray : [IndexPath] = [IndexPath]() 

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let myCell = tableView.cellForRow(at: indexPath) as! TableCell 
    myCell.resourceIcons.image = UIImage(named: "RubiusResources2") 
    tableView.deselectRow(at: indexPath, animated: true) 

    if(!selectedArray.contains(indexPath)) 
    { 
     selectedArray.append(indexPath) 
    } 
    else 
    { 
     // remove from array here if required 
    } 
} 

,然後在cellForRowAt,寫這樣的代碼來設置適當的圖像

​​