0

I have two class. Class 1(a CollectionViewController) has a function, I need call this func in Class 2(a 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()

    }
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272
Rasputin
  • 21
  • 3
  • possible duplicate of https://stackoverflow.com/questions/30541010/how-to-reload-data-in-a-tableview-from-a-different-viewcontroller-in-swift/30541063 – Leo Dabus Aug 20 '19 at 18:49

2 Answers2

0

Yeah, don't do that. The code you wrote creates a brand-new instance of HomeController and attempts to invoke its closeSideMenu() method. 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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Don't put code in comments. The lack of formatting makes them unreadable. Instead edit your question and add the additional code. – Duncan C Aug 20 '19 at 18:53
  • yeah as I said I am the novice about swift. I wondering how can I handle this problem ? how can I to throw a bridge between two cars ? Can you send an example to me ? – Rasputin Aug 20 '19 at 19:02
-1

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