![](/img/trans.png)
[英]How to store multiple selected row items in mutable array in tableview
[英]Store TableView selected Row
我有一個表格視圖,我想更改所選表格視圖的選定單元格顏色,並且在滾動表格視圖時不更改單元格顏色。 有我的代碼:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath
indexPath: NSIndexPath) {
let selectCell = tableView.indexPathForSelectedRow
self.selectedCell.append(selectCell!)
for i in selectedCell
{
if(!(i .isEqual(indexPath)))
{
let currentCell = tableView.cellForRowAtIndexPath(i)! as UITableViewCell
currentCell.backgroundColor = UIColor.lightGrayColor()
}
}
滾動表視圖時,這就是代碼崩潰。
您的代碼對我來說似乎很奇怪。 您無需每次選擇所有其他單元格的背景顏色。 將celectedCells
定義為Int:Bool
類型的字典,這樣就可以將每個indexpath.row
值設置為true
,如下所示:
var selectedCells = [Int: Bool]()
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.backgroundColor = UIColor.lightGrayColor()
selectedCells[indexPath.row] = true
}
}
然后在您的cellForRowAtIndexPath
方法中檢查該字典以設置backgroundColor,如下所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier", forIndexPath: indexPath)
if selectedCells[indexPath.row] == true {
// Color for selected cells
cell.backgroundColor = UIColor.lightGrayColor()
} else {
// Color for not selected cells
cell.backgroundColor = UIColor.whiteColor()
}
//Rest of your Cell setup
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.