gpt4 book ai didi

ios - 在 Swift 中通过 Storyboard Segue 传递自定义初始化参数

转载 作者:搜寻专家 更新时间:2023-10-31 19:39:43 24 4
gpt4 key购买 nike

我对自定义初始化程序的概念有些陌生,所以我很难理解我尝试做的事情是否可行。

我正在使用源代码创建消息应用程序。所有代码都是在不使用 Storyboard的情况下编写的,我现在想实现它。

在源代码中实现的 init 是这样的:

init(chat: Chat) {
self.chat = chat
super.init(nibName: nil, bundle: nil)
title = chat.user.name
}

required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

didSelectRowAtIndexPath 方法中,原始代码以这种方式传递自定义初始化参数:

 let chat = chats[indexPath.row]
let chatViewController = MessagesViewController(chat: chat)
navigationController?.pushViewController(chatViewController, animated: true)

我尝试做的是简单地创建一个 Storyboard UIViewController,将类设置为原始代码,即将 Storyboard ViewController 设置为:MessagesViewController,然后执行 segue。像这样:

if segue.identifier == "ToMessages" {
var messagesViewController: MessagesViewController = segue.destinationViewController as MessagesViewController
let chat = chats[indexPath.row]
messagesViewController.chat = chat
}

然后 performSegueWithIdentifier("ToMessages", sender: self)

当我这样做时,我得到了这个 fatal error :fatal error: init(coder:) has not been implemented:

根据我对原始源代码的研究和理解,原因是我没有初始化chat参数。我意识到我可能不在正确的轨道上,如果是的话,我将不胜感激。

如果我对发生的事情是正确的,那么我的具体问题是如何在 prepareForSegue 方法中实现参数,例如:

var destinationVC = segue.destinationViewController as MessagesViewController(chat: chat)

最佳答案

问题不是因为您没有初始化聊天参数,而是因为您没有在 initWithCoder 中调用 super。这是为 Storyboard中的 View 调用的方法,因此您只需设置聊天属性而不是使用自定义初始化程序,就像您在上一个代码片段中显示的那样。由于您没有在 int 方法中执行任何操作,因此您可以将它们全部删除。如果出于其他目的需要将它们放在那里,则只需从 initWithCoder 中删除“ fatal error ”行,并将其替换为对 super 的调用。

关于ios - 在 Swift 中通过 Storyboard Segue 传递自定义初始化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375753/

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