🎃
【Swift】Button & Actions in TableView Cells【コピペコード】
【「ViewController」のコード】
import UIKit
class ViewController: UIViewController,UITableViewDataSource {
@IBOutlet var tableView: UITableView!
let data = ["First","Second","Third","Another","More"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(MyTableViewCell.nib(), forCellReuseIdentifier: MyTableViewCell.identifier)
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MyTableViewCell.identifier, for: indexPath) as! MyTableViewCell
cell.configure(with: data[indexPath.row])
cell.delegate = self
return cell
}
}
extension ViewController: MyTableViewCellDelegate {
func didTapButton(with title: String) {
print("\(title)")
}
}
【「MyTableViewCell」のコード】
import UIKit
protocol MyTableViewCellDelegate: AnyObject {
func didTapButton(with title: String)
}
class MyTableViewCell: UITableViewCell {
weak var delegate: MyTableViewCellDelegate?
static let identifier = "MyTableViewCell"
static func nib() -> UINib {
return UINib(nibName: "MyTableViewCell", bundle: nil)
}
@IBOutlet var button: UIButton!
private var title: String = ""
@IBAction func didTapButton() {
delegate?.didTapButton(with: title)
}
func configure(with title: String) {
self.title = title
button.setTitle(title, for: .normal)
}
override func awakeFromNib() {
super.awakeFromNib()
button.setTitleColor(.link, for: .normal)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
参考動画
Button & Actions in TableView Cells in Swift 5 (Xcode 12 - 2023)
Discussion