SWIFT: Trigger function from TableCell

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • robertybob
    New Member
    • Feb 2013
    • 116

    SWIFT: Trigger function from TableCell

    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, ParentViewContr oller, 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.
  • robertybob
    New Member
    • Feb 2013
    • 116

    #2
    I solved this using NSNotificationC enter - 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 'addButtonPress ed' deals with the processing
    Code:
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "addButtonPressed", name: "addToList", object: nil)

    Custom Cell

    For the custom cell I needed to call a function there using the following.
    Code:
    addToListButton.addTarget(self, action: "addListPressed", forControlEvents: .TouchUpInside)
    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.
    Code:
    func addListPressed(sender:UIButton) {
            myListButton = sender
            NSNotificationCenter.defaultCenter().postNotificationName("addToList", object: nil)
     }
    Hope this can help someone save some time and effort even if not a perfect solution.

    Comment

    Working...