カスタムセルとボタンの両方のデリゲートを作成する必要があります。
//here is the view controller class
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CustomCellDelegate {
var firstChoice = 0
var selections = Array<Any>()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as? CustomCell
cell?.delegate = self
return cell!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func cellButtonTapped(_ cell: CustomCell) {
if cell.isSelected {
firstChoice = 1
selections.append(firstChoice)
}
}
}
カスタムセルクラス
protocol CustomCellDelegate {
func cellButtonTapped(_ cell: CustomCell)
}
class CustomCell: UITableViewCell, CustomButtonDelegate {
var delegate: CustomCellDelegate?
@IBOutlet weak var button1: CustomButton!
@IBOutlet weak var button2: CustomButton!
@IBOutlet weak var button3: CustomButton!
override func awakeFromNib() {
super.awakeFromNib()
button1.delegate = self
button2.delegate = self
button3.delegate = self
}
func buttonTapped() {
self.isSelected = !self.isSelected
if let delegate = delegate {
delegate.cellButtonTapped(self)
}
}
}
そしてカスタムボタンそのプロトコルと
protocol CustomButtonDelegate{
func buttonTapped()
}
class CustomButton: UIButton {
var delegate: CustomButtonDelegate?
override func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
func buttonTapped(_ sender: AnyObject) {
if let delegate = delegate {
delegate.buttonTapped()
}
}
}
それらの両方
を参照してください:http://stackoverflow.com/questions/ 20655060/get-button-click-inside-ui-table-view-cell –