如何使用带委托的协议将ViewController中的字符串值传递到容器中?
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) {
}
}
我一直得到错误“在隐式展开可选值时意外找到nil”。但据我所知,价值并不为零。它正在打印出来。它只是不会传递给文本标签
最佳答案
你应该把集装箱装上
let containerV = self.storyboard!.......
不
let containerV = ContainerView()
因为它使所有的出口都为零
在风险投资被提出之前,不要进入它的出口
ViewC.delegate?.passData(theData: "pass this text")
因为即使你从情节串连板加载它,在加载之前输出也是零