【问题标题】:How can I call a method that is inside a UIViewController embedded in a container from a parent UIViewController?如何从父 UIViewController 调用嵌入在容器中的 UIViewController 内的方法?
【发布时间】:2016-04-04 09:23:07
【问题描述】:

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

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

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

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

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


    }



}

还有我的 embedController:

protocol HandleEmbedController: class {
    func printMsg()
}

class EmbedController: UITableViewController, HandleEmbedController{

    var value1 = ""

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

}

如何从父控制器打印此消息?

【问题讨论】:

    标签: ios swift uiviewcontroller protocols


    【解决方案1】:

    你在为 Segue 做哪些准备?你不应该在那里设置你的代表(协议)吗?像这样:

    if (segue.identifier == "embedViewSegue"){
    
        if let embed = segue.destinationViewController as? EmbedController     {
            self.handleEmbedController = embed
        }
    
    }
    

    如果您在sendMsgButtonAction 中放置断点,您应该会看到属性handleEmbedController 为nil。这就是为什么方法调用什么都不做的原因,因为您使用? 安全地打开它。

    【讨论】:

    • 谢谢,那是我缺少的一部分!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 2021-03-15
    • 2012-05-03
    相关资源
    最近更新 更多