UITableViewCell 내부 버튼 클릭 이벤트

JG Ahn·2024년 11월 28일
0

iOS

목록 보기
5/32
post-thumbnail

팀 프로젝트를 하면서 UITableView를 다루게 되어 알아보게 되었다.

테이블뷰의 셀 안에 있는 버튼이 클릭되었을 때 동작하도록 설정하려면, 버튼의 액션을 처리하기 위해 델리게이트 패턴을 활용할 수 있다.

  1. UITableViewCell 클래스 생성
import UIKit

// 프로토콜 정의
protocol tableViewCellDelegate: AnyObject {
    func didTapButton(in cell: TableViewCell)
}

class TableViewCell: UITableViewCell {
    weak var delegate: tableViewCellDelegate?

    // 버튼 생성
    private let actionButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Click Me", for: .normal)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        return button
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.addSubview(actionButton)
        setupConstraints()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupConstraints() {
        actionButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            actionButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
            actionButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            actionButton.widthAnchor.constraint(equalToConstant: 80),
            actionButton.heightAnchor.constraint(equalToConstant: 40)
        ])
    }

    @objc private func buttonTapped() {
        delegate?.didTapButton(in: self)
    }
}
  1. ViewController에서 UITableView 구현
    TableViewCell의 델리게이트 메소드를 구현해서 버튼 클릭 이벤트를 처리
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TableViewCellDelegate {
    private let tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)

        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")

        tableView.frame = view.bounds
    }

    // UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell else {
            return UITableViewCell()
        }
        cell.delegate = self // 델리게이트 설정
        return cell
    }

    // TableViewCellDelegate
    func didTapButton(in cell: TableViewCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        // 버튼 클릭에 따른 추가 동작
    }
}

더 자세한 내용은 추후 추가하도록 해야겠다...

0개의 댓글