I have been working on an app where I need to put a UICollectionView inside UITableViewCell. Each UICollectionViewCell has two buttons which I need to handle in my TableViewController class. So I added targets to those buttons to call a method in my TableViewCell class as I am setting each CollectionViewCell from there. Then, I have a custom delegate method that is called from that method and I have implemented that method in my TableViewController class. Everything works as expected unless I press the home button on my device and then return to the app. The method in the TableViewCell class is still being called but not the one in my TableViewController class.
This is my protocol and handler
protocol CollectionViewCellButtonPressHandlerDelegate {
func handle(button: UIButton?, data: Any?)
}
class CollectionViewCellButtonPressHandler {
var delegate: CollectionViewCellButtonPressHandlerDelegate?
func handle(button: UIButton?, data: Any?) {
if self.delegate != nil {
delegate?.handle(button: button, data: data)
}
}
}
Apart from setting the TableViewCell, this is the code that is in my TableViewController's cellForRowAtIndexPath method
cell.handler = CollectionViewCellButtonPressHandler()
cell.handler.delegate = self
cell.goalCollectionView.reloadData()
This is my implementation of the delegate method in my TableViewController class.
func handle(button: UIButton?, data: Any?) {
if let msg = data as? String {
print(msg)
}
}
This is how I have set the target to the button in cellForRowAtIndexPath method of my TableViewCell class
cell.playButton.addTarget(self, action: #selector(self.play(sender:)), for: .touchUpInside)
This is the implementation of the play button action in my TableViewCell class
func play(sender: UIButton) {
for i in 0..<goals.count {
let indexPath = IndexPath(row: i, section: 0)
if let cell = self.goalCollectionView.cellForItem(at: indexPath) as? GoalCollectionViewCell {
if sender == cell.playButton {
print("Play: ", self.goals[indexPath.row].subskill!)
self.handler.handle(button: sender, data: self.goals[indexPath.row])
}
}
}
}
The print statement above the delegate method is executed even after returning from background but the next statement is not. I have also checked for the handler and its delegate to be nil but they were not. Please help.
CollectionViewCellButtonPressHandlerDelegate
)? UITableViewCOntroller or UITableViewCell? – Minahandle
function inCollectionViewCellButtonPressHandler
is a random function which has the same name and structure as your delegate functionfunc handle(button: UIButton?, data: Any?)
? – Mina