gpt4 book ai didi

ios - 如何从父 UIViewController 调用容器中嵌入的 UIViewController 中的方法?

转载 作者:行者123 更新时间:2023-11-29 01:05:43 25 4
gpt4 key购买 nike

我有一个 swift 的 ios 应用程序,并且有一个带有容器的 UIViewController (我们称之为parentController)。该容器嵌入了另一个名为 embedController 的 UIViewController。

embedController 包含一个将消息打印到控制台的方法。

如何从我的 parentController 调用此方法?

我尝试使用协议(protocol),我目前的代码如下:

class ParentController: UIViewController {

var handleEmbedController:HandleEmbedController?


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "embedViewSegue"){

if let embed = segue.destinationViewController as? EmbedController {
embed.value1 = value1
}

}

@IBAction func sendMsgButtonAction(sender: AnyObject) {

handleEmbedController?.printMsg() //this so far does nothing


}



}

和我的嵌入 Controller :

protocol HandleEmbedController: class {
func printMsg()
}

class EmbedController: UITableViewController, HandleEmbedController{

var value1 = ""

func printMsg(){
print("printing some embedded message")
}

}

如何从父 Controller 打印这条消息?

最佳答案

您在为 segue 做准备时正在做什么?你不应该在那里设置你的代表(协议(protocol))吗?像这样:

if (segue.identifier == "embedViewSegue"){

if let embed = segue.destinationViewController as? EmbedController {
self.handleEmbedController = embed
}

}

如果您在 sendMsgButtonAction 中放置断点,您应该会看到属性 handleEmbedController 为 nil。这就是方法调用不执行任何操作的原因,因为您正在使用 ? 安全地解包它。

关于ios - 如何从父 UIViewController 调用容器中嵌入的 UIViewController 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36398807/

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