iOS 3D touch 使用技巧

第一个 在桌面中3d Touch 打开菜单  

由于本人纯属代码党,本次实现方法也只使用代码实现

到达到这个效果并不难,只需要在appdelegate中实现以下代码即可 ,当然也有缺点,就是这个app没运行过的话是用不了3dtouch呼出菜单

 1 - (void)setting3DTouchModule{
 2     // 判断系统版本大于9.0再设置 (若不判断 在低版本系统中会崩溃)
 3     if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0){
 4         
 5         // 自定义图标
 6         UIApplicationShortcutIcon *icon1 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"图片名称"];
 7         
 8         UIApplicationShortcutItem *shortItem1 = [[UIApplicationShortcutItem alloc] initWithType:@"item类型1" localizedTitle:@"item标题1" localizedSubtitle:@"子标题1" icon:icon1 userInfo:nil];
 9         
10         UIApplicationShortcutItem *shortItem2 = [[UIApplicationShortcutItem alloc] initWithType:@"item类型2" localizedTitle:@"item标题2" localizedSubtitle:@"子标题2" icon:[UIApplicationShortcutIcon iconWithType: UIApplicationShortcutIconTypeCompose] userInfo:nil];
11         
12         // item 数组
13         NSArray *shortItems = [[NSArray alloc] initWithObjects: shortItem1,shortItem2, nil];
14         
15         // 设置按钮
16         [[UIApplication sharedApplication] setShortcutItems:shortItems];
17     }
18     
19 }
20 // 通过3dtouch菜单启动 后回调
21 - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler{
22     // 可以通过标题 字符串判断 来确认 是哪个item
23     if ([shortcutItem.localizedTitle  isEqualToString: @"item标题1"]){
24 
25     }
26 }

didFinishLaunchingWithOptions方法中执行 

    [self setting3DTouchModule];

即可

第二种效果   触发机制 参考 微信朋友圈 3dtouch打开图片 

这个由于涉及到tableview /collectionview中cell的重用机制(如果你只给某个view加入 3dtouch手势的话可以无视), 需要对cell做一定的自定义操作

我这里以collectionview为例,在回调cell 的方法里,将当前controller对象传入cell中进行 3DTouch事件注册

而正常添加3dtouch只需要下面这一句代码

[self registerForPreviewingWithDelegate:self sourceView:cell.contentView];  //正常添加3DTouch事件

添加3DTouch的controller 要遵循UIViewControllerPreviewingDelegate协议

然后实现 两个代理方法

- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit{
    // 打开详情页触发
    if (viewControllerToCommit){
        [self showViewController:viewControllerToCommit sender:self];
    }
}
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location{
     // 这里要返回要打开的viewController
     return nil;  
}

具体实现 可以参考我的demo

再者就是下面的按钮

加入购物车 这个按钮是需要我们在 回调的那个controller中实现以下代码

1 - (NSArray<id<UIPreviewActionItem>> *)previewActionItems{
2     UIPreviewAction *itemA = [UIPreviewAction actionWithTitle:@"加入购物车" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
3         NSLog(@"你要做的操作");
4     }];
5     return @[itemA];
6 }

具体请参考demo

http://files.cnblogs.com/files/n1ckyxu/IOS_3DTouch_Demo.zip

原文地址:https://www.cnblogs.com/n1ckyxu/p/5096316.html