gpt4 book ai didi

ios - 在哪里快速设置委托(delegate)?

转载 作者:行者123 更新时间:2023-11-29 05:52:49 28 4
gpt4 key购买 nike

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

感谢您的见解,我才刚刚开始!

我尝试在不同位置设置委托(delegate)(目前在 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 协议(protocol)符合函数 (func statusChanged) 应执行。

实际:什么也没发生

最佳答案

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?

关于ios - 在哪里快速设置委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55514099/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com