1

我的应用程序的条目ViewController包含两个按钮:weightage。在 mainViewController中,这是单击weight按钮时运行的代码:

@IBAction func weightSearch(_ sender: Any) {
//Weight button clicked
inputReset()
userInput.keyboardType = UIKeyboardType.numberPad
userInput.becomeFirstResponder()
}

这是单击age按钮时运行的代码:

@IBAction func ageSearch(_ sender: Any) {
    //Age button clicked
    inputReset()
    userInput.inputView = agePicker
    userInput.becomeFirstResponder()
}

我要做的是实现两个 3D Touch 快速操作,一个称为Weight Search(运行代码func weightSearch),另一个称为Age Search(运行代码func ageSearch)。这是我到目前为止所做的:

  1. Info.plist文件中,我创建了一个UIApplicationShortcutItems数组,其中包含两个Items字典类型,以及它们各自的UIApplicationShortcutItemTitleUIApplicationShortcutItemType.
  2. 在我的AppDelegate.swift文件中,我添加了初步的快速操作代码:

    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    //3D touch features 
    }
    

我现在的问题是我不确定要为我的AppDelegate.swift文件编写什么代码。我看过的所有教程和该站点上的所有类似问题都涉及ViewController使用快速操作调用不同的函数,而不是在同一个 `ViewController. 先感谢您。

4

1 回答 1

1

因为 iOS 告诉您AppDelegate用户选择了快速操作,所以您可以随意使用它。要获得对您的参考,您ViewController只需询问windowrootViewController这将是您的ViewController)。然后你就可以自由地做你需要做的事情了。

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
  guard let viewController = window?.rootViewController as? ViewController else { return }
  viewController.performSomeAction()
}

如果将来某个时间点您更改为具有不同类型的视图控制器作为根,您还可以在将来证明这一点并在调试模式下运行时崩溃:

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
  guard let viewController = window?.rootViewController as? ViewController else { 
  assertionFailure("Wrong view controller type!") // This only crashes in debug mode
  return 
}
  viewController.performSomeAction()
}
于 2017-07-13T20:32:02.143 回答