这并不难,正如您所提到的,有很多教程可以提供帮助。总之,首先您需要将 3d 触摸代理添加到您的 ViewController.h 或 .m。 <UIViewControllerPreviewingDelegate>
这将使您能够访问显示主屏幕快捷方式所需的委托方法。这是我的一个应用程序的示例(在此示例中删除了名称)。
在我的 AppDelegate 中,首先调用performActionForShortcutItem:completionHandler: 并发送用户选择的快捷方式。使用它来确定如何响应快捷方式。我将快捷方式传递给一个方法,handleShortcutItem:shortcutItem",它将确定我将使用哪个故事板(我知道 iPad 中现在没有 3D Touch,但我想在 Apple 推出时构建代码 em>)。
基于快捷方式,我创建我的 ViewController 并将快捷方式传递给方法logShortcutUsed,并传入快捷方式标题。
#pragma mark - Shortcut Items
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
completionHandler([self handleShortcutItem:shortcutItem]);
}
- (BOOL)handleShortcutItem:(UIApplicationShortcutItem *)shortcutItem {
UIStoryboard *storyboard;
UINavigationController *navController = (UINavigationController *) self.window.rootViewController;
if (IS_IPAD()) {
storyboard = [UIStoryboard storyboardWithName:@"Main_iPad" bundle:nil];
} else {
storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
}
xxxViewController *vb = (xxxViewController *)navController.topViewController;
if ([shortcutItem.localizedTitle isEqualToString:@"New Match"]) {
[vb logShortcutUsed:shortcutItem.localizedTitle];
[vb startNewMatch];
return TRUE;
} else if ([shortcutItem.localizedTitle isEqualToString:@"New Game"]) {
[vb logShortcutUsed:shortcutItem.localizedTitle];
[vb gamePressedFromShortcut];
return TRUE;
}
return FALSE;
}
在我的主 ViewController 中,我创建了动态快捷方式(您可以使用静态或动态快捷方式)。这是用户在 3D Touch 图标时看到的内容。我还包括一个图标,这是可选的。 shortcutItems 只是 UIApplicationShortcutItems 的数组。
- (void)setupDynamicShortcuts {
UIApplicationShortcutItem *newMatch = [[UIApplicationShortcutItem alloc] initWithType:@"$(PRODUCT_BUNDLE_IDENTIFIER).NewMatch"
localizedTitle:NSLocalizedString(@"New Match", @"Start a new match")
localizedSubtitle:NSLocalizedString(@"Start a new match", @"Start a new match button.")
icon:[UIApplicationShortcutIcon iconWithTemplateImageName:@"Sport Net-50"]
userInfo:nil];
UIApplicationShortcutItem *newGame = [[UIApplicationShortcutItem alloc] initWithType:@"$(PRODUCT_BUNDLE_IDENTIFIER).NewGame"
localizedTitle:NSLocalizedString(@"New Game", @"Start a new game")
localizedSubtitle:NSLocalizedString(@"Start a new game", @"Start a new game button.")
icon:[UIApplicationShortcutIcon iconWithTemplateImageName:@"volleyball-50"]
userInfo:nil];
[UIApplication sharedApplication].shortcutItems = @[newMatch, newGame];
}
在同一个 ViewController 中是将从 AppDelegate、startNewMatch 和 gamePressedFromShortcut 调用的方法。我还将这些调用记录到我的分析中,以便跟踪人们使用此功能的次数,这是我强烈建议的。
这并不像最初看起来那么困难。