Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] allowsMultipleSelection, tableView cell 멀티 선택 방법, checkBox 만드는 방법 본문

iOS 응용 (swift)

[iOS - swift] allowsMultipleSelection, tableView cell 멀티 선택 방법, checkBox 만드는 방법

jake-kim 2021. 8. 25. 23:44

tableView. allowsMultipleSelection = true 설정하여 구현

CheckBoxCell 구현

  • isCheck라는 property가 있고, 이 property를 통해 check되면 체크 이미지를 업데이트하고 값을 가지고 있는 상태
    // CheckboxCell.swift
    var isCheck: Bool = false {
        didSet {
            let imageName = isCheck ? "checkmark.square" : "checkmark.square.fill"
            checkBoxButton.setImage(UIImage(systemName: imageName), for: .normal)
        }
    }
  • cell이 check되는지 확인은 UITableViewCell에서 제공하는 setSelected(:animated:)를 override하여 사용
    // CheckboxCell.swift
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        isCheck.toggle()
    }

TableView 생성

  • tableView.allowsMultipleSelection = true 속성을 통해 checkBox형태로 되도록 수정
    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(tableView)
        tableView.register(CheckboxCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.allowsMultipleSelection = true

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 12).isActive = true
        tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -12).isActive = true
        tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 120).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -120).isActive = true
    }

* 전체 코드: https://github.com/JK0369/TableView_multi_selection

Comments