swift - 如何使用 applicationWillResignActive 调用 View Controller 的函数

标签 swift xcode delegates appdelegate

当按下主页按钮时,或者当用户接到电话等时,我试图在我的 View Controller 中调用我的菜单 View ......

我的目标是调用函数:toggleMenu(),它位于 QuestionViewController 中。这是代码:

class QuestionViewController: UIViewController, MFMailComposeViewControllerDelegate {

///////////

    func toggleMenu() {

    // Show or hide menu

    if menuStackView.isHidden == true {

        // Show the menu
        print("Showing Menu")
        // Update labels
        questionNumberMenuLabel.text = questionNumberLabel.text
        endTimer()
        menuStackView.isHidden = false
        animateInMenu()


    } else {

        // Hide the menu
        animateOutMenu()

    }
}

我相信我应该使用 AppDelegate.swift 文件中的以下方法:

    func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

如果我在正确的轨道上,我需要帮助在此方法中调用 QuestionViewController 类的 toggleMenu() 函数。我该怎么做?

非常感谢!

最佳答案

使用 NotificationCenter 并监听 UIApplicationWillResignActiveNotification。系统广播该通知并调用您的应用委托(delegate)的 applicationWillResignActive 方法(假设您有一个方法。)

监听通知(在你的viewDidLoad中使用方法addObserver(forName:object:queue:using:)。如果你不需要支持iOS版本<9.0,你不需要不必担心调用 removeObserver - 系统会为您处理。

关于swift - 如何使用 applicationWillResignActive 调用 View Controller 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49566342/

相关文章:

C++ - 如何将类上的所有成员函数调用委托(delegate)给同一接口(interface)的成员

ios - If else语句取决于文本字段(swif3)

swift - UITextChecker、Swift 的单词学习——不起作用

ios - Swift 错误 - 调用 SimpleAuth 时的额外参数 'option'

ios - swift 3 : How to add or remove parameters in Request Body in ALamofire 4?

ios - 找不到接受提供的参数 SWIFT 的 “init” 的重载

ios - UITableView 中的单元格问题

C# 委托(delegate)中动态链接变量值的问题

swift - 我需要创建一组按钮,然后删除它们并创建新的组

swift - 如何使用 SwiftUI 对可隐藏 View 进行动画处理?