I have a UITapGestureRecognizer attached to an image within a tableview cell in Swift.
When the user taps the image, I'd like to access a property (variable) of the View Controller containing the tableview cell but I can't seem to do that.
The property in the View controller is defined as:
@objcMembers class myVC : UIViewController,UITableViewDelegate, UITableViewDataSource,UITextViewDelegate {
var lastUserMessage = "test"
}
The gesture recognizer function is defined within a custom tableViewCell as follows
class MyImageCell : UITableViewCell {
@objc func didTapImage(gesture: UITapGestureRecognizer) {
print("someone tapped image")
print("self is",self)
/*
prints: myApp.MyImageCell: 0x7f8668045e00; baseClass = UITableViewCell; frame = (0 347; 393 175.667); clipsToBounds = YES; autoresize = W; animations = { <UIMotionEffectGroup: 0x60000089c8a0>=<CAAnimationGroup: 0x60000089d380>; }; layer = <CALayer: 0x600000882a40>>
*/
print("lastUserMessage is",lastUserMessage)//prints nil
print("MyVC.shared.lastUserMessage is",MYVC.shared.lastUserMessage)//prints nil
}
How can I access the variable of the VC from within the tableviewcell. Seems like it should not be that difficult?
Anthropic AI suggests the following but creating an entire new delegate protocol seems really difficult for what should be a straightforward task...
To access the property of a view controller from within a table view cell in Swift, you can use the delegate pattern. First, create a protocol with a method that includes the property you want to access. Then, make your view controller conform to this protocol and set the cell's delegate to the view controller. In the cell, call the method on the delegate to access the property. This way, you can access the view controller's property without directly coupling the cell and the view controller.
If you want to give info about your ViewController to your Cell no need Delegate Pattern or Callbacks. You can change your cell from your stubs.But don't forget to apply tableview and datasource to your ViewController itself. If you want to get information about your cell from ViewController then you need to apply Callback or Delegate Pattern.
@objcMembers class myVC : UIViewController,UITableViewDelegate, UITableViewDataSource,UITextViewDelegate {
var lastUserMessage = "test"
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ID", for: indexPath) as! MyImageCell
cell.lastUserMessage = self.lastUserMessage
return cell
}
}
class MyImageCell : UITableViewCell {
var lastUserMessage = ""
@objc func didTapImage(gesture: UITapGestureRecognizer) {
print("someone tapped image")
print("print ",lastUserMessage)
}
}