팀 프로젝트를 하면서 UITableView를 다루게 되어 알아보게 되었다.
테이블뷰의 셀 안에 있는 버튼이 클릭되었을 때 동작하도록 설정하려면, 버튼의 액션을 처리하기 위해 델리게이트 패턴을 활용할 수 있다.
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)
}
}
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 }
// 버튼 클릭에 따른 추가 동작
}
}
더 자세한 내용은 추후 추가하도록 해야겠다...