Jochen Österreicher Jochen Österreicher - 18 days ago 13
iOS Question

swift 3 call function from parent ViewController

I have a ViewController, this view container has a class which creates 2 container views, and adds a table to the first container and a HashtagPicker for the second.

The hashTagPicker has a function which is called whenever a change to the selected hashTags happens.

question: i want to call a update table function whenever a tag is changed. How can i call a function from the hashtagclass which is defined in the class that contains the containers?

Answer

You can use delegate/protocols for this

First create Protocol in your HashtagPicker class

protocol HashTagPickerDelegate {

   func hastagPicked(hashtag:String)
}

Now create an object for this protocol in HashtagPicker class

class HashtagPicker : UIViewController
{

  var delegate: HashTagPickerDelegate?

}

Now call the protocol method using this delegate object when user selects the hashtag from table view (from didSelectRow method)

delegate.hashtagPicked(pickedHashtag)

Don't forget to register protocol in Parent view,

class ParentView:UIViewController, HashTagPickerDelegate
{

}

And set the parentView as the delegate object for the HastagPicker, as you are using containers you can do it from prepareForSegue method. Don't forget to set segue id for container segue.

func prepare(for segue: UIStoryboardSegue, sender: AnyObject?)
{
  if segue.identifier == "HastagPickerSegue" // use your segue id here
  {
    let hashtagPicker = segue.destinationViewController as! HashtagPickerView
    hashtagPicker.delegate = self
   } 
}