简体   繁体   English

如何从另一个控制器类调用函数?

[英]How can I call a func from another controller class?

I have two class. 我有两个班。 Class 1(a CollectionViewController) has a function, I need call this func in Class 2(a TableviewController). 1类(CollectionViewController)具有一个功能,我需要在2类(TableviewController)中调用此函数。 Can anyone help me about this problem ? 有人可以帮我解决这个问题吗? I did it like below but it is not working. 我做到了,如下所示,但它不起作用。

extension MenuController {

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("clicked menu item...")
        let sideMenuContorller = HomeController()
        sideMenuContorller.closeSideMenu()

    }
}

Yeah, don't do that. 是的,不要那样做。 The code you wrote creates a brand-new instance of HomeController and attempts to invoke its closeSideMenu() method. 您编写的代码创建了HomeController的全新实例,并尝试调用其closeSideMenu()方法。 That won't work. 那行不通。

(An analogy: You want to change the station on your car's radio. You build a brand-new car, set the station on that car's radio, throw the new car away, and then wonder why your car's radio station hasn't changed.) (打个比方:你想改变你的车的广播电台为您打造一个全新的车,设置在该车上的广播电台,抛出新的车开走,然后不知道为什么你的车的广播电台并没有改变。 )

How do these two view controllers get created? 如何创建这两个视图控制器? You need to explain how those view controllers get created an how they are associated with each other. 您需要解释如何创建这些视图控制器,以及它们如何相互关联。

Somehow, your MenuController need a reference to the existing HomeController . 不知何故,您的MenuController需要对现有 HomeController的引用。

I think you can use something called delegates here is an example : 我认为您可以使用称为“委托”的示例:

    protocol ClickedMenuItemDelegate {
     func userDidPressedMenuItem()
    }

    class MenuController {
     delegate: ClickedMenuItemDelegate?
      override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        delegate?.userDidPressedMenuItem()
       }
    }

    class HomeController: ClickedMenuItemDelegate {
    // where you create an object of type MenuController you first set its delegate property
     menuControllerInstace.delegate = self
     func userDidPressedMenuItem() {
       closeSideMenu()
    }

The idea is that when you call delegate?.userDidPressedMenuItem() the code inside the userDidPressedMenuItem() method in the class where you set delegate = self gets called You can find more details here : https://learnappmaking.com/delegation-swift-how-to/ https://docs.swift.org/swift-book/LanguageGuide/Protocols.html 这个想法是,当您调用委托?.userDidPressedMenuItem()时,将在您设置委托= self的类中的userDidPressedMenuItem()方法内的代码被调用。您可以在此处找到更多详细信息: https : //learnappmaking.com/delegation-swift -how-to / https://docs.swift.org/swift-book/LanguageGuide/Protocols.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM