XIB 和 View Controller 之间的协议委托

Protocol Delegate between XIB and View Controller

所以我有 XIB 视图和视图控制器。我想要当我的 XIB 中的一个按钮被点击时(didTapTryAgain 按钮),从我的视图控制器中调用一个函数。然后我尝试为 class 创建一个协议和委托。但它仍然不会调用我的函数。这是我的 XIB 视图 class:

import UIKit

protocol ErrorMessageDelegate {
    func refresh(_sender: AnyObject)
}

class ErrorMessage: UIView {
    @IBOutlet weak var imageViewError: UIImageView!
    @IBOutlet weak var labelError: UILabel!
    @IBOutlet weak var buttonTryAgain: UIButton!
    static weak var shared: ErrorMessage?
    var delegate: ErrorMessageDelegate?
    static var message: String?

    override func awakeFromNib() {
        ErrorMessage.shared = self
        labelError.text = ErrorMessage.message
    }

    @IBAction func didTapTryAgain(_ sender: UIButton) {
        delegate?.refresh(_sender: buttonTryAgain)
    }
}

这是我的视图控制器 class:

import Foundation

class BaseViewController: UIViewController, ErrorMessageDelegate {

    func refresh(_sender: AnyObject) {
        print("I hope my function work here")
    }

    var uiView =  UIView();

    override func viewDidLoad() {
        super.viewDidLoad()
        ErrorMessage.shared?.delegate = self
    }

    func getErrorMessage(message:String) {
        super.viewDidLoad()
        Dialog.dismiss()
        ErrorMessage.message = message
        guard let viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as? ErrorMessage else { return}
        self.view.addSubview(viewErrorMessage)
    }
}

我正在关注 我的代码,但它仍然无法正常工作。有人知道怎么做吗?谢谢!

您的问题是您在此处为共享实例设置了委托

ErrorMessage.shared?.delegate = self / here shared?. is nil

但是这里

guard let viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as? ErrorMessage else { return}
self.view.addSubview(viewErrorMessage)

您创建一个单独的实例并添加它

你需要

var viewErrorMessage:ErrorMessage! // add to the vc

viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as! ErrorMessage 
viewErrorMessage.delegate = self
self.view.addSubview(viewErrorMessage)

也完全git摆脱

static weak var shared: ErrorMessage?

只需使用这段代码,您的委托方法就会被调用。

  func getErrorMessage(message:String) {
    ErrorMessage.message = message
    guard let viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as? ErrorMessage else { return}
    viewErrorMessage.delegate = self
    self.view.addSubview(viewErrorMessage)
}

并在您想要打开弹出窗口的位置调用方法

getErrorMessage(message: "Test Message")