LoginSignup
2
1

More than 5 years have passed since last update.

Swift3 テーブルをスクロールするとチェックマークが勝手につく場合の解決法

Posted at

Swift3 テーブルをスクロールするとチェックマークが勝手につく場合の解決法

やりたいこと

ある値に合致した場合にのみテーブルで表示しているセルにチェックマークを付けたいがテーブルをスクロールするとチェックマークを付けたいセル以外にもチェックマークが勝手についたり、ずれたりする現象を解決したい

動作環境

  • Xcode9.2
  • Swift3

原因

どうやらセルの再利用に関する問題のようで、下記のようにテーブルにチェックマークをつける条件分岐を片方でしか行わなかった場合発生した。



import UIKit

class viewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

// ... 中略 ...

    /// セルの表示内容を操作するメソッド
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // ここでは事前に定義しておいたStoryboardのセルを指定
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellName", for: indexPath as IndexPath)
        cell.textLabel?.text = alphabet[indexPath.row]
        if cell.textLabel?.text == "a" {
           cell.accessoryType = .checkmark
        } 
        return cell
    }
}

解決策

チェックマークをつける際は条件分岐でつけない場合の処理もきちんと記載することで回避できた



import UIKit

class viewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

// ... 中略 ...

    /// セルの表示内容を操作するメソッド
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // ここでは事前に定義しておいたStoryboardのセルを指定
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellName", for: indexPath as IndexPath)
        cell.textLabel?.text = alphabet[indexPath.row]
        if cell.textLabel?.text == "a" {
           cell.accessoryType = .checkmark
        } else {
           cell.accessoryType = .none // 条件に当てはまらなかった場合、チェックマークをつけない記述を追記
        }
        return cell
    }
}

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1