7

I have two ViewController's.

  1. FirstVC - I have label and button with segue "modal"

  2. SecondVC - I have PickerView and button (back to FirstVC):

    @IBAction func bntback(sender: AnyObject) {
              self.dissmissViewControllerAnimatied(true, completion: nil)
        }
    

And I created delegate in SecondViewController as:

protocol SendDataDelegate {
   func sendData(text:String)
}

Next:

class SecondVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
      var delegate: SendDataDelegate!
      var firstvc = FirstVC()
      var arr = ["First", "Second", "Third"]
      @IBOutlet var pickview: UIPickerView!
      override func viewDidLoad() {
         super.viewDidLoad()
         pickview.dataSource = self
         pickview.selegate = self
     }

My function of PickerView and in this function I use my delegate as:

func pickerView (pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
  var text = arr[row]
  dispatch_async(dispatch_get_main_quene(), {
  self.delegate.sendData(text)//there is an error: "fatal error: unexpectedly found nil while unwrapping an Optional value"
  )}
}

FirstVC:

class FirstVC: UIViewController, SendDataDelegate {
      var data = SecondVC()
      //....
      override func viewDidLoad() {
         super.viewDidLoad()
         self.data.delegate = self
     }
     func sendData (text:String) {
        mylable.text = text
        //or 
        //var txt = text
       //mylable.text = txt
     }
 }

Help me please with this problem.

1
  • var data = SecondVC() cannot work because there is already an instance of SecondVC created in Interface Builder. The usual way to set the delegate is in prepareForSegue Commented Jun 26, 2015 at 14:05

1 Answer 1

8

1) You need to set delegate into prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let viewController = segue.destinationViewController as? SecondVC {
        viewController.delegate = self
    }
}

UPDATE:

2) Set delegate as Optional

class SecondVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    var delegate: SendDataDelegate?
    ...

    func pickerView (pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        var text = arr[row]
        dispatch_async(dispatch_get_main_quene(), {
            self.delegate?.sendData(text)
        )}
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.