LoginSignup
49
48

More than 5 years have passed since last update.

【Swift】UITableViewのセルにチェックマークを入れる方法

Last updated at Posted at 2016-10-23

単一選択

デモ

select.gif

コード

ViewController.swift
import UIKit

class CustomerSettingViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let fruits = ["Orange","Lemon", "Peaches", "Raspberry", "Papaya", "Avocado", "Blueberries", "Apricot", "Mango"]

    override func viewDidLoad() {
        super.viewDidLoad()

        let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
        let displayWidth: CGFloat = self.view.frame.width
        let displayHeight: CGFloat = self.view.frame.height
        let tableView: UITableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

        tableView.dataSource = self
        tableView.delegate = self

        // trueで複数選択、falseで単一選択
        tableView.allowsMultipleSelection = false

        tableView.tableFooterView = UIView(frame: .zero)

        self.view.addSubview(tableView)
    }

    // セルが選択された時に呼び出される
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at:indexPath)

        // チェックマークを入れる
        cell?.accessoryType = .checkmark
    }

    // セルの選択が外れた時に呼び出される
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at:indexPath)

        // チェックマークを外す
        cell?.accessoryType = .none
    }

    // セルの数を返す
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return fruits.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "\(fruits[indexPath.row])"

        // セルが選択された時の背景色を消す
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        return cell
    }
}

複数選択

デモ

multiselect.gif

コード

上記コードのtableView.allowsMultipleSelection = falsetrueに変更するだけ。

49
48
1

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
49
48