grjr02
grjr02

Reputation: 35

How would I pass data using protocols from my View Controller to a container within it?

How would I pass the string value in my ViewController into the Container using a protocol with a delegate?

protocol VCDelegate {
    func passData(theData:String)        
}

class ViewController: UIViewController {

var delegate : VCDelegate?

@IBAction func getRestaurantInformation(_ sender: Any) {

    let ViewC = ViewController()
    let ContainerV = ContainerView()      

    ViewC.delegate = ContainerV
    ViewC.delegate?.passData(theData: "pass this text")

}
override func viewDidLoad() {

    super.viewDidLoad()

}


class ContainerView: UIViewController, FirstVCDelegate {


func passData(theData: String) {

    print(theData)
    textLabelOut.text = theData //it leaves an error "found nil while implicitly unwrapping optional value"

}


@IBOutlet weak var textLabelOut: UILabel!

override func viewWillAppear(_ animated: Bool) {

}
}

I keep getting the error "Unexpectedly found nil while implicitly unwrapping an Optional value". But from what I understand the value isn't nil. It is printing out. It just wont pass it to the text label

Upvotes: 1

Views: 38

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

You should load the container with

let containerV = self.storyboard!.......

not

let containerV = ContainerView()      

as it makes all outlets nil


Don't access outlets of a vc until it's presented

ViewC.delegate?.passData(theData: "pass this text")

because even if you load it from storyboard , also outlets are nil until it loads

Upvotes: 1

Related Questions