【Swift】セルの選択状態(タップ時の色)を解除する

解説

 

TableViewのCellをタップすると、そのCell全体が灰色に染まってしまう。

f:id:nekokichi_yos2:20181203201926p:plain

 

しかも、他のCellをタップしない限り、元の白色に戻ることはない。

 

タップ時の変化自体を削除することも可能だが、タップしても何も変化が起こらないと、ユーザーにとってはどのCellをタップしたのかがわからない。

 

できれば、

 

Cellをタップ

Cellが灰色に

処理実行

Cellが白色に

 

という流れを実装したい。

 

そこで役立つのが、deselectRow()、だ。

 

これを使えば、Cellのタップ時、Cellの色がスーッと白色に戻る。

 

ソースコード

 

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{
    
    @IBOutlet weak var tableView: UITableView!
    
    var array = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let a = UserDefaults.standard.array(forKey: "配列") as? [String] {
            array = UserDefaults.standard.array(forKey: "配列") as! [String]
            tableView.reloadData()
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = array[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let DC = self.storyboard?.instantiateViewController(withIdentifier: "detail") as! DetailController
        DC.indexNum = indexPath.row
        DC.label = array[indexPath.row]
        self.navigationController?.pushViewController(DC, animated: true)
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    @IBAction func addButton(_ sender: Any) {
        performSegue(withIdentifier: "Add", sender: nil)
    }
    
}