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()
}
}
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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.