How do I handle a custom UIView button action inside a TableViewCell?
I have custom UIView with XIB which I added to TableView which is implementet in UIViewControler. For each cell I add my custom UIView in tableView function - cellForRowAt. Everything looks fine but I can't handle button action from added custom UIView for that cell. Can someone help me how to do that?
Edit:
My custom UIView which has own XIB.
protocol TicketButtonDelegate {
func starButtonAction(_: UIButton)
}
class TicketView: UIView {
@IBOutlet var ticketContentView : UIView!
var delegate: TicketButtonDelegate!
@IBOutlet weak var starButton : UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func commonInit() {
Bundle.main.loadNibNamed("TicketView", owner: self, options: nil)
addSubview(ticketContentView)
starButton.addTarget(self, action: #selector(starButtonAction(_:)), for: .touchUpInside)
ticketContentView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 132)
}
@objc func starButtonAction(_ sender: UIButton) {
delegate.starButtonAction(sender)
}
}
My UIViewController.
class MhdDashboardBottom: UIViewController, TicketButtonDelegate {
@IBOutlet weak var mhdTicketsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
mhdTicketsTable.delegate = self
mhdTicketsTable.dataSource = self
mhdTicketsTable.register(UINib(nibName: "MhdTicketTableCell", bundle: nil), forCellReuseIdentifier: "MhdTicketCell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "MhdTicketCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MhdTicketTableCell else {
fatalError("The dequeued cell is not an instance of MhdTicketTableCell")
}
let ticket = tickets[indexPath.row]
let ticketCell = TicketView()
ticketCell.delegate = self
ticketCell.tag = 700
var viewExists = false
for view in cell.contentCellView.subviews {
if view.tag == ticketCell.tag {
viewExists = true
break
}
}
if viewExists == false {
cell.contentCellView.addSubview(ticketCell)
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 132
}
func starButtonAction(_: UIButton) {
print("Works?")
}
}
My MhdTicketTableCell (UITableViewCell)
class MhdTicketTableCell: UITableViewCell {
@IBOutlet weak var contentCellView: UIView!
}