0

您好,我最近在课程中遇到了协议和委托(此处为 iOS 开发人员)。

我试图在我的简单应用程序中应用它,它基本上什么都不做,但我想将数据从一个 VC 传递到另一个。

更具体地说:ViewControllerOne 有按钮并设置转到我的 ViewControllerTwo,ViewControllerTwo 也有按钮,我现在只想在单击 ViewControllerTwo 上的按钮时打印一些文本。

这是代码:

接收者

    class ViewControllerOne: UIViewController, DataDelegate {
      var vcTwo = ViewControllerTwo()        

      override func viewDidLoad() {
       super.viewDidLoad()
    
      vcTwo.delegate = self
      }
    
      func printThisNumber(type: Int){
        print("This is a test of delegate with number: \(type)")
      }
    

定义了协议的发送方

protocol DataDelegate {
  func printThisNumber(type: Int)
}

class ViewControllerTwo: UIViewController {

  var delegate: DataDelegate?

  override func viewDidLoad() {
    super.viewDidLoad()
  }



  @IBAction func myButtonPressed(_ sender: UIButton) {
     delegate?.printThisNumber(type: 1)

  }
}

它什么也没发送,我试图用 print 语句显示 nil 来解决它,显然(当单击按钮时),但即使我在 viewDidLoad 中打印委托,它也显示为 nil。

当我尝试使用 StackOverflow 的另一种方法时,比如将委托声明为弱 var,Xcode 甚至不允许我这样做。

感谢任何将他/她的时间花在这个问题上并提出任何可以帮助我理解或解决问题的人。

如果能解决这个问题,我未来的打算是获取一些关于 VCTwo 的数据并使用这些数据进行更新,例如 VCOne 上的标签文本。

谢谢你最好的问候彼得

4

1 回答 1

1

由于您使用 segue 导航到ViewControllerTwo,因此vcTwoin 中的实例ViewControllerOne不会是推送的视图控制器实例。您必须覆盖prepare(for segueinViewControllerOne才能访问该实例ViewControllerTwo,然后设置委托。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vcTwo = segue.destination as? ViewControllerTwo {
        vcTwo.delegate = self
    }
}
于 2020-08-07T15:49:42.627 回答