gpt4 book ai didi

ios - XIB 和 View Controller 之间的协议(protocol)委托(delegate)

转载 作者:搜寻专家 更新时间:2023-11-01 06:53:11 25 4
gpt4 key购买 nike

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

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对于我的代码,它仍然无法正常工作。有人知道怎么做吗?谢谢!

最佳答案

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

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?

关于ios - XIB 和 View Controller 之间的协议(protocol)委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55745602/

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