【问题标题】:How to send data with Protocols and Delegate with IBAction (Button click)如何使用协议发送数据并使用 IBAction 委托(按钮单击)
【发布时间】:2020-08-07 14:37:58
【问题描述】:

您好,我最近在课程中遇到了协议和委托(此处为 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 上的标签文本。

谢谢 最好的祝福 彼得

【问题讨论】:

  • 您在 ViewControllerOne 中创建了 vcTwo,但是一旦您进行了 segued,ViewControllerOne 可能已经清除,因此 vcTwo。在任何情况下,您在 segue 时都会创建一个新的 vcTwo 实例。你能展示一下你是如何触发 segue 和准备函数的吗?在准备中,您应该为 vcTwo 设置委托。比如 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? ViewControllerTwo {destination.delegate = self
  • @claude31 感谢您的评论,正如您所写,也如下所述,我有我的准备功能,并定义了目的地,但没有提及目的地.delegate = self

标签: ios swift swift-protocols swift-class


【解决方案1】:

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

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vcTwo = segue.destination as? ViewControllerTwo {
        vcTwo.delegate = self
    }
}

【讨论】:

  • 感谢您的回复,它成功了,我忘记在我准备segue时,提到“vcTwo.delegate = self”部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多