【Swift】セルをタップ時、セルの色を自由に変更する

完成図

 

f:id:nekokichi_yos2:20181109140741p:plain

 

解説

 

 ・cell.selectionTypeに用意されたプロパティ(.none, .blue, .gray)を設定するだけ

・自分好みの色に設定するなら、

  1. UIViewを生成
  2. UIVIewの背景色を設定
  3. cell.selectedBackgroundViewにUIViewを代入

をするだけ

 

ソースコード

 

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    //セルのテキストを格納
    var array = ["AAA","BBB","CCC"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //これを追加するだけ
        tableView.tableFooterView = UIView()
    }
    
    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: "reuseIdentifier", for: indexPath)
        
        //これでセルをタップ時、色は変化しなくなる
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        //自分で色を設定したい場合は、タップ時の色を指定したUIViewを代入
        let selectionView = UIView()
        //タップすると赤色になる
        selectionView.backgroundColor = UIColor.red
        cell.selectedBackgroundView = selectionView
        
        cell.textLabel?.text = array[indexPath.row]
        return cell
    }

}