我在使用应用程序中的3D触摸快捷方式时遇到了问题。我的应用程序使用选项卡,但我想将用户重定向到选项卡,然后当他们按下创建愿望清单按钮时,也将其重定向到另一个segue。
Here is a picture of my storyboard.
我目前使用的代码显示了主视图控制器,但我希望它进入创建愿望列表控制器。
我在app delegate中使用句柄快捷键的代码如下:
func handleShortcut( shortcutItem:UIApplicationShortcutItem ) -> Bool {
print("Handling shortcut")
var succeeded = false
if( shortcutItem.type == "com.example.Giftr" ) {
print("- Handling \(shortcutItem.type)")
if let tabVC = self.window?.rootViewController as? UITabBarController{
tabVC.selectedIndex = 1
//This is where I need to swap to the "createwishlist" view controller.
}
为了解决这个问题,我使用了一个全局变量来存储已经在appDelegate中获取的快捷方式,如下所示。
GlobalVars.shortcut = 1
let tabVC = window?.rootViewController as! UITabBarController
print(tabVC.self)
tabVC.selectedIndex = 0
然后在选项卡的控制器内为selectedIndex 0检查该值是否为1,然后它是否被调到我想要结束的视图控制器。如图所示。
override func viewDidAppear(animated: Bool) {
if(GlobalVars.shortcut == 1)
{
self.performSegueWithIdentifier("shortcut", sender: self)
GlobalVars.shortcut = 0
}
}
确保将全局变量设置为0,否则每次出现视图时都会调用此变量。
在成功切换选项卡后,这应该能够将ViewController更改为所需的类。
let vc = ViewController() //change this to your class name
self.presentViewController(vc, animated: true, completion: nil)
我会使用NotificationCenter。假设您的应用程序自然启动到HomeViewController,它恰好是主标签栏控制器的第一个VC,并且您想要定义“New Post”快捷项目,以便在加载HomeViewController时它会执行segue到NewPostViewController。
首先,定义通知名称:
extension Notification.Name {
Notification.Name("applicationLaunchedWithNewPostShortcutItem")
}
其次,使用快捷项启动应用程序时发布通知(我假设它是第一个静态快捷项):
func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem) -> Bool {
var handled = false
guard ShortcutIdentifier(fullType: shortcutItem.type) != nil else { return false }
guard let shortCutType = shortcutItem.type as String? else { return false }
switch shortCutType {
case ShortcutIdentifier.first.type:
NotificationCenter.default.post(name: .applicationLaunchedWithNewPostShortcutItem, object: nil, userInfo: nil)
handled = true
break
default:
break
}
return handled
}
对于那些不熟悉上述方法的人,它通常在AppDelegate.swift中定义,并在appDelegate.swift中的应用程序(_:performActionFor:completionHandler :)中调用。请参阅Apple的示例代码here。
最后,允许HomeViewController通过实现广告观察者()并删除其中的Observer()方法来调入通知。
class HomeViewController {
// MARK: - View Controller Life Cycle
override func viewDidLoad() { // or viewWillAppear(), etc.
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: .applicationLaunchedWithNewPostShortcutItem, object: nil, queue: .main) { [weak self] (notification) in
self?.handleApplicationLaunchedWithNewPostShortcutItem(notification: notification)
}
}
deinit { // or viewWillDisappear(), etc.
removeObservers()
}
// MARK: - Notification Center Handlers
private func handleApplicationLaunchedWithNewPostShortcutItem(notification: Notification) {
performSegue(withIdentifier: "presentNewPost", sender: nil)
}