469,342 Members | 5,847 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,342 developers. It's quick & easy.

SWIFT: Trigger function from TableCell

116 64KB
Hi.

I have a ViewController, say HomeView.
It contains a TableView, say MyTable.
The table has a custom cell of class MyCell.

How can I assign delegates, protocol or whatever is needed to get a button click (addTarget method) within MyCell to trigger a function in main ViewController, HomeView?

I can't seem to use self, ParentViewController, HomeView() to get error free code.

I did manage to get the iOS Simulator to work by using 'HomeView()' instead of 'self' in the addTarget but the actual device doesn't seem to like that at all.

Thanks.
Feb 7 '16 #1
1 4893
robertybob
116 64KB
I solved this using NSNotificationCenter - not sure that this is really the best method but anything that works when it comes to Swift is ok with me.

Main Controller

Added the following to the ViewDidLoad where 'addButtonPressed' deals with the processing
Expand|Select|Wrap|Line Numbers
  1. NSNotificationCenter.defaultCenter().addObserver(self, selector: "addButtonPressed", name: "addToList", object: nil)
  2.  

Custom Cell

For the custom cell I needed to call a function there using the following.
Expand|Select|Wrap|Line Numbers
  1. addToListButton.addTarget(self, action: "addListPressed", forControlEvents: .TouchUpInside)
  2.  
The function 'addListPressed' then has the following code to report back to the parent controller to complete the action where 'myListButton' is a global variable storing the button pressed.
Expand|Select|Wrap|Line Numbers
  1. func addListPressed(sender:UIButton) {
  2.         myListButton = sender
  3.         NSNotificationCenter.defaultCenter().postNotificationName("addToList", object: nil)
  4.  }
  5.  
Hope this can help someone save some time and effort even if not a perfect solution.
Feb 9 '16 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Steven Wu | last post: by
2 posts views Thread by Jules Alberts | last post: by
2 posts views Thread by Karl O. Pinc | last post: by
5 posts views Thread by Peter Erickson | last post: by
reply views Thread by Dennis Gearon | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by haryvincent176 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.