我正在练习如何使用协议和委托在两个视图控制器之间进行通信(在 xCode 背景中,即使我在项目中使用协议,我也会遇到同样的问题,委托为零),但是在设置它向我显示的所有内容后出现问题我的委托为零,并且发送者 VC 不发送任何数据,因为委托为零。
我已经确认了协议,并将接收方 VC 设置为委托,但仍然看不出问题出在哪里。
协议
protocol theCommunicationsStructionProtocol{
func dataToTransmit(Data: String)
}
Run Code Online (Sandbox Code Playgroud)
发送者 VC
class TheSenderVC{
var delegate: theCommunicationsStructionProtocol?
func lookingForDelegate(){
self.delegate?.dataToTransmit(Data: "Data has been sent")
}
}
Run Code Online (Sandbox Code Playgroud)
接收器VC
class TheReceiverVc1: theCommunicationsStructionProtocol{
var TheSenderVCObj = TheSenderVC()
func delegateLuncher(){
TheSenderVCObj.delegate = self
}
func dataToTransmit(Data: String) {
print("from VC1: \(Data)")
}
}
Run Code Online (Sandbox Code Playgroud)
调用 delegateLuncher() 在接收者 VC 中设置委托
TheSenderVC().lookingForDelegate()
Run Code Online (Sandbox Code Playgroud)
从发送方 VC 调用lookingForDelegate() 来查找委托并向其发送数据
TheReceiverVc1().delegateLuncher()
Run Code Online (Sandbox Code Playgroud)
注意:我尝试使用以下方式从接收者 VC 访问委托:
class TheReceiverVc1: theCommunicationsStructionProtocol{
var TheSenderVCObj: TheSenderVC?
func delegateLuncher(){
self.TheSenderVCObj?.delegate = self
} …Run Code Online (Sandbox Code Playgroud)