2

プロジェクトに UITableView Controller があります。そこで、次のように 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
}

インデックスが2で割り切れない場合、テーブルビューのセルを灰色にしたい.

tableview が表示されたら、すべてが完璧です。しかし、上下にスクロールすると、セルの色が灰色に変わり始めます。

最後に、すべてのセルが灰色になります。

ここにいくつかの画像があります:

4

3 に答える 3

2

問題は、背景を白に戻さないことです。セルは再利用されるため、ある時点ですべてのセルをグレーに設定します。代わりに、セルが再利用されるたびに行インデックスを確認する必要があります。

cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.white : UIColor.gray
于 2016-10-16T12:14:58.460 に答える