在哪里迅速设置代表?

时间:2019-04-04 10:52:34

标签: ios swift delegates

我已经建立了一个简单的Swift项目,试图将我的头放在委托和协议上。目标是在两个类(SendingClassReceivingClass)之间传递数据。 SendingClass中的两个按钮链接到代理,该代理应触发ReceivingClass中符合协议的函数执行。不幸的是,这行不通,我怀疑这与我将ReceivingClass声明为委托人的位置和方式有关。

感谢您的见解,我才刚刚起步!

我尝试将委托设置在各个位置(目前在viewDidLoad内,但是无法正常工作)。

let vc = SendingClass()
vc.statusDelegate = self

SendingClass.swift

import UIKit


protocol StatusDelegate {
    func statusChanged(state: Bool, sender: String)
}

class SendingClass: UIViewController {

    var statusDelegate : StatusDelegate?


    @IBAction func button1Pressed(_ sender: UIButton) {
      statusDelegate?.statusChanged(state: true, sender: "Button 1")
    }

    @IBAction func button2Pressed(_ sender: UIButton) {
        statusDelegate?.statusChanged(state: false, sender: "Button 2")
    }

}

ReceivingClass.swift

import Foundation
import UIKit

class ReceivingClass: UIViewController, StatusDelegate {

    override func viewDidLoad() {
        let vc = SendingClass()
        vc.statusDelegate = self
    }

    func statusChanged(state: Bool, sender: String) {
        print("Sender = \(sender) , State = \(state)")
    }
}

预期:每次在SendingClass中按下按钮时,ReceivingClass符合协议的功能(func statusChanged)应该执行。

实际:什么都没发生

3 个答案:

答案 0 :(得分:0)

I am using this..
// create extension in your receiving class
extension ReceivingClass: PopUpVCDelegate {
   func statusChanged(state: Bool, sender: String) {
        print("Sender = \(sender) , State = \(state)")
    }
}

// on sending class, when you present your receiving class on any button click
eg.
let resultController = self.storyboard?.instantiateViewController(withIdentifier: "PopUpVCID") as? PopUpVC       

        resultController?.delegate = self
  self.present(resultController!, animated: true, completion: nil)

 //or if not have button add on viewdidload in receiving class

// here is full eg

How to get data from popup view controller to custom table view cell?

答案 1 :(得分:0)

对于协议和委托,当您要将第二个VC(由第一个VC表示或由第一个VC推送)中的值带到原始的第一个VC时,可以使用它。 从您的代码中,我看不到您介绍或推送您的第二个VC。这就是为什么它不起作用。希望我回答了您的疑问。

但是,如果您仍然希望将值从第一VC转移到第二VC。在第二个VC中,创建一个变量以接收它

var ReceivedData = String()

然后从您的第一个VC开始,当您要推送它时,

let vc = SendingClass()
vc.ReceivedData = "Whatever you want it to receive"

答案 2 :(得分:0)

如果您正在使用情节提要剧集,则可能从那里实例化了视图控制器,因此可能您必须使用prepareForSegue并在{{1中为目标实例化控制器。 }}视图控制器:

ReceivingClass

也要注意委托模式:委托属性应声明为override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let destination = segue.destination as? SendingClass { destination.delegate = self } } 属性,以避免保留周期

weak