【问题标题】:How to use applicationWillResignActive to call a function of a view controller如何使用 applicationWillResignActive 调用视图控制器的功能
【发布时间】:2018-03-29 23:13:06
【问题描述】:

我试图在按下主页按钮时调用我的视图控制器内的菜单视图,或者当用户接到电话等时......

我的目标是调用 QuestionViewController 中的函数:toggleMenu()。代码如下:

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() 函数。我该怎么做?

非常感谢!

【问题讨论】:

    标签: swift xcode delegates appdelegate


    【解决方案1】:

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

    监听通知(在 viewDidLoad 中使用 addObserver(forName:object:queue:using:) 方法。如果您不需要支持 iOS 版本

    【讨论】:

    • 谢谢!我是 Xcode 和 Swift 的新手,所以其中一些仍然在我的脑海中。我尝试添加这行代码: override func viewDidLoad() { super.viewDidLoad() // Listen to notifications addObserver(observer: NSObject, forKeyPath: String, options: NSKeyValueObservingOptions, context: UnsafeMutableRawPointer 但这与您的不同观察者函数。另外我不知道如何为您前面提到的 applicationWillResignActive 方法设置应用程序委托。我使用 prepareforsegue 在 VC 之间发送数据
    • 不要超过 cmets 中的代码片段。缺乏格式使其不可读。返回并编辑您的问题,在底部添加和##EDIT: 标签,并在那里显示您的新代码
    • 谢谢!我是 Xcode 和 Swift 的新手,所以其中一些仍然在我的脑海中。我尝试添加这行代码。但这与您的观察者功能不同。此外,我不知道如何为您之前提到的 applicationWillResignActive 方法设置应用程序委托。我使用 prepareforsegue 在 VC 之间发送数据 ##EDIT: override func viewDidLoad() { super.viewDidLoad() // 监听通知 addObserver(observer: NSObject, forKeyPath: String, options: NSKeyValueObservingOptions, context: UnsafeMutableRawPointer
    • 射击,我想不通。让我试试这个……(见下一条评论)
    • override func viewDidLoad() { super.viewDidLoad() // 监听通知 addObserver(observer: NSObject, forKeyPath: String, options: NSKeyValueObservingOptions, context: UnsafeMutableRawPointer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多