2016-10-16 11 views
2

私のプロジェクトにUITableViewコントローラがあります。だから私はここのようにUITableViewCellのセットアップを行った。そのインデックスはテーブルビューが表示されます。2.スクロールでUITableViewCellの背景設定がリセットされる

で割り切れない場合

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

    cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)." 

    if indexPath.row % 2 == 1 { 
     cell.backgroundColor = UIColor.gray 
    } 

    return cell 
} 

は私が私のテーブルビューのセルが灰色になりたい、すべてが完璧です!しかし、上下にスクロールすると、セルの色がグレーに変わります。

最終的に私の細胞はすべて灰色です。ここで

は、いくつかの画像です:

before

after

答えて

3

は、細胞が再利用されているので、elseステートメントを追加してください。

else { 
    cell.backgroundColor = UIColor.white 
} 
+0

おかげで多くのことを)それはとても簡単だった):!D –

+0

@AlexVihlayev問題ありませんメイト。 :) –

0

テーブルビューは、細胞

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)." 

if indexPath.row % 2 == 1 { 
    cell.backgroundColor = UIColor.gray 
}else{ 
    cell.backgroundColor = YOUR_COLOR 
} 
return cell 

}

編集を再利用するので:ゲラート・リーはこの問題は、あなたが戻って白に背景を設定したことがないということである最初にそれに答えて、非常にシンプルな

2

。セルは再利用されているので、ある時点でそれらのすべてに対してグレーを設定します。代わりに、毎回セルが再利用された行のインデックスをチェックする必要があります!

cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.white : UIColor.gray 
関連する問題