2016-09-19 6 views
-1

私はテーブルビューを持っています。選択したテーブルビューを選択したセルの色に変更したいです。私のコードがあります:TableViewを選択した行を保存します。

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() 
      } 
     } 

スクロールテーブルビューではコードがクラッシュします。

+0

選択時にdidSelectRowAtIndexPathに現在のindexpath.rowを格納する変数を作成します。現在のindexpath.rowのcellForRowAtIndexPathの内部を確認します。格納されているindexpath.rowが一致する場合は、色を変更します。 – Tuhin

+0

選択したすべてのインデックスカラーを変更する必要がありますか? –

+0

選択したすべての行の色を変更する必要がある場合は、選択したインデックスをdidSelectRowAtIndexPathメソッドの配列に保存し、cellForRowAtIndexPathメソッドで、配列内にインデックスパスがあるかどうかをチェックし、それに応じて処理します –

答えて

2

あなたのコードは私にとって非常に奇妙なようです。 1つを選択するたびに他のすべてのセルの背景色を設定する必要はありません。このように、

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 
} 
タイプ Int:Boolの辞書ので、あなたは、このような各 indexpath.rowため trueに設定することができますようご celectedCellsを定義します
関連する問題