ios - NSObject Delegate类,将Delegate传递给UIViewcontroller类

标签 ios swift uiviewcontroller delegates nsobject

所以我有一个 NSObject 类型的网络 Controller 类,并且在其中我有一个委托(delegate)协议(protocol):

protocol NetworkControllerDelegate: class {
func stateChanged(_ state: NetworkState)
func setNotInMatch()
func player(_ playerIndex: UInt8, movedToPosX posX: Int)
func matchStarted(_ match: Match)
}

我有一个 UIViewController 类型的 ViewController,它尝试接收委托(delegate)更新,但它不起作用。在我的网络 Controller 中我设置:

var delegate: NetworkControllerDelegate?

我还触发了委托(delegate)函数

delegate?.matchStarted(match!)

在 UIViewController 中,我遵守委托(delegate)并监听,但没有任何反应

class ConnectPlayerViewController: UIViewController, NetworkControllerDelegate {
func stateChanged(_ state: NetworkState) {
    print("stateChanged")
}

func setNotInMatch() {
    print("sentNotInMatch")
}

func player(_ playerIndex: UInt8, movedToPosX posX: Int) {
    print("recieved Player Update")
}

let networkhandler = NetWorkController()
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func ConnectUser(_ sender: UIButton) {
    networkhandler.connect()
}
func matchStarted(_ match: Match) {
    print(match)
}

}

networkhandler.connect() 只是调用网络 Controller 中的一个函数,最终触发委托(delegate),委托(delegate)被触发,但我的 UIViewController 中没有收到它,我在网上阅读过,但它们似乎都来自UIViewController 到 UIViewController。不过,我不是在 View 之间导航,而是调用应该触发委托(delegate)的 NSObject 类。

最佳答案

所以这个问题的答案实际上很简单,我只需添加:

networkhandler.delegate = self

  override func viewDidLoad() {
    super.viewDidLoad()
    networkhandler.delegate = self
    // Do any additional setup after loading the view.
}

关于ios - NSObject Delegate类,将Delegate传递给UIViewcontroller类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48594268/

相关文章:

ios - NSPersistentContainer 仅适用于 10.0 或更新版本 : error

ios - 在 iOS WebView 中获取 PDF 文档高度

ios - 在 Swift 中不是初始的主从 View

objective-c - 我应该在哪里设置 ViewController 中的 subview 框架

ios - 无法分配类型为 '(String!, Bool, [AnyObject]!, NSError!)->Void to a value of type UIActivityViewControllerCompletionWithItemsHandler?' 的值

android - 如何从付费应用转换为应用内购买? iOS和Android + Flutter

swift - 调用中缺少参数 #4 的参数会忽略闭包

Swift,将数据从弹出窗口传回 View Controller

ios - AVPlayer 不从子域的 url 加载视频

ios - 在没有 Storyboard的情况下更改 View Controller