XIB和View Controller之间的协议委托

时间:2019-04-18 11:59:58

标签: ios swift delegates protocols xib

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

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)
    }
}

这是我的View Controller类:

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)
    }
}

我正在遵循this answer的代码,但仍然无法正常工作。有人知道怎么做吗?谢谢!

2 个答案:

答案 0 :(得分:1)

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

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)

也完全摆脱了

static weak var shared: ErrorMessage?

答案 1 :(得分:1)

只需使用此代码,即可调用您的委托方法。

  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")