iOS 3D Touch使用简介

什么是3D Touch

3D Touch是iOS9中引入的新的人机交互方式,它允许用户按压屏幕预览内容或者打开快捷键。

Home Screen Quick Actions(主页快捷键)

用力按压主页的应用图标,会显示主页快捷键。如图:
img

静态配置快捷键

需要在info.plist文件中手动配置,如下图:

img

一些主要的key:

UIApplicationShortcutItems:数组中的元素就是我们的那些快捷选项标签。

UIApplicationShortcutItemTitle:标签标题(必填)

UIApplicationShortcutItemType:标签的唯一标识(必填)

UIApplicationShortcutItemIconType:使用系统图标的类型,如搜索、定位、home等(可选)

UIApplicationShortcutItemIconFile:使用项目中的图片作为标签图标(可选)

UIApplicationShortcutItemSubtitle:标签副标题(可选)

UIApplicationShortcutItemUserInfo:字典信息,如传值使用(可选)

动态配置快捷键(代码添加)

/**
 创建应用图标上的3D touch快捷选项
 */
- (void)creatShortcutItem {
    //创建系统风格的icon
//    UIApplicationShortcutIcon *icon = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeAdd];

    //创建自定义图标的icon
//    UIApplicationShortcutIcon *icon2 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"分享.png"];

    //创建快捷选项
    UIApplicationShortcutItem *shareItem = [[UIApplicationShortcutItem alloc] initWithType:@"com.cxy.-DTouch.share" localizedTitle:@"分享" localizedSubtitle:@"分享联系人信息" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeShare] userInfo:nil];
    UIApplicationShortcutItem *searchItem = [[UIApplicationShortcutItem alloc] initWithType:@"com.cxy.-DTouch.search" localizedTitle:@"搜索" localizedSubtitle:@"搜索联系人" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeSearch] userInfo:nil];
    UIApplicationShortcutItem * addItem = [[UIApplicationShortcutItem alloc] initWithType:@"com.cxy.-DTouch.add" localizedTitle:@"添加" localizedSubtitle:@"添加联系人到通讯录" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeAdd] userInfo:nil];

    //添加到快捷选项数组
    [UIApplication sharedApplication].shortcutItems = @[shareItem, searchItem, addItem];
//    UIApplicationShortcutItem *shortcutItem = [launchOptions valueForKey:UIApplicationLaunchOptionsShortcutItemKey];
}

然后在application:didFinishLaunchingWithOptions:方法中调用即可

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //创建应用图标上的3D touch快捷选项
    [self creatShortcutItem];
    return YES;
}

动态修改shortcutItem:

/**
 改变快捷按钮显示文字
 */
- (void)changeShortcutItem {
    //将shortcutItem0的类型由UIApplicationShortcutItem改为可修改类型UIMutableApplicationShortcutItem
    UIApplicationShortcutItem *shortcutItem0 = [[UIApplication sharedApplication].shortcutItems objectAtIndex:0];
    UIMutableApplicationShortcutItem * newShortcutItem0 = [shortcutItem0 mutableCopy];
    //修改shortcutItem的标题
    [newShortcutItem0 setLocalizedTitle:@"按钮1"];
    //将shortcutItems数组改为可变数组
    NSMutableArray *newShortcutItems = [[UIApplication sharedApplication].shortcutItems mutableCopy];
    //替换原ShortcutItem
    [newShortcutItems replaceObjectAtIndex:0 withObject:newShortcutItem0];
    [UIApplication sharedApplication].shortcutItems = newShortcutItems;
}

响应相应快捷键操作

/**
 如果是从快捷选项标签启动app,则根据不同标识执行不同操作,然后返回NO,防止调用

 @param application       <#application description#>
 @param shortcutItem      <#shortcutItem description#>
 @param completionHandler <#completionHandler description#>
 */
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
    if (shortcutItem) {
        //判断先前我们设置的快捷选项标签唯一标识,根据不同标识执行不同操作
        if([shortcutItem.type isEqualToString:@"com.cxy.-DTouch.share"]) {//进入分享界面
            NSArray *arr = @[@"3D Touch 分享"];
            UIActivityViewController *vc = [[UIActivityViewController alloc] initWithActivityItems:arr applicationActivities:nil];
            [self.window.rootViewController presentViewController:vc animated:YES completion:^{

            }];
        } else if ([shortcutItem.type isEqualToString:@"com.cxy.-DTouch.search"]) {//进入搜索界面
//            NSArray *arr = @[@"3D Touch 搜索"];
//            UISearchController *searchVC = [[UISearchController alloc] init];
//            searchVC.title = @"搜索";
//            [(UINavigationController *)self.window.rootViewController pushViewController:searchVC animated:YES];
            UIViewController *vc = [UIViewController new];
//            [vc.view addSubview:searchVC.searchBar];
            [self.window.rootViewController presentViewController:vc animated:YES completion:^{

            }];
        } else if ([shortcutItem.type isEqualToString:@"com.cxy.-DTouch.add"]) {//进入分享界面
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *addContactsVC = [storyboard instantiateViewControllerWithIdentifier:@"AddContactsViewController"];
            [(UINavigationController *)self.window.rootViewController pushViewController:addContactsVC animated:YES];
        }
        completionHandler(YES);
    }
    return completionHandler(NO);
}

peek(轻压展示预览)和pop(用力按压直接跳页至预览的界面)

首先给view注册3DTouch的peek(预览)和pop功能,我这里给cell注册3DTouch的peek(预览)和pop功能

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ReuseID = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ReuseID];
    }
    cell.textLabel.text = self.dataArray[indexPath.row];
    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        NSLog(@"3D Touch  可用!");
        //给cell注册3DTouch的peek(预览)和pop功能
        [self registerForPreviewingWithDelegate:self sourceView:cell];
    } else {
        NSLog(@"3D Touch 无效");
    }
    return cell;
}

需要继承协议UIViewControllerPreviewingDelegate

实现UIViewControllerPreviewingDelegate方法

//peek(轻按预览)
- (nullable UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
    //获取按压的cell所在行,[previewingContext sourceView]就是按压的那个视图
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell* )[previewingContext sourceView]];

    //设定预览的界面
    PreviewViewController *childVC = [PreviewViewController new];
    childVC.preferredContentSize = CGSizeMake(0.0f,500.0f);
    NSString *str = [NSString stringWithFormat:@"我是%@,用力按一下进来", self.dataArray[indexPath.row]];
    childVC.str = str;
    //调整不被虚化的范围,按压的那个cell不被虚化(轻轻按压时周边会被虚化,再少用力展示预览,再加力跳页至设定界面)
    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width,40);
    previewingContext.sourceRect = rect;

    //返回预览界面
    return childVC;
}

//pop(按用点力进入)
- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    [self showViewController:viewControllerToCommit sender:self];
}

增加预览操作

在预览界面控制器中重写previewActionItems方法,在其中自定义预览操作和事件回调。

- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {
    // setup a list of preview actions
    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"Aciton1" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"Aciton1");
        ActionViewController *actionVC = [ActionViewController new];
        [(UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController pushViewController:actionVC animated:YES];
    }];
    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"Aciton2" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"Aciton2");
    }];
    UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"Aciton3" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"Aciton3");
    }];
    NSArray *actions = @[action1,action2,action3];
    return actions;
}


效果图:(当用户按下时cell周边会虚化,增加压力达到一定值会弹出设定的预览界面,继续增加力按压会跳页至预览界面)

img

force属性

iOS9以后, UITouch类增加了2个新属性force和maximumPossible以支持自定义3D Touch. force属性是CGFloat类型,表示压力大小,在一个范围类动态变化。用例:

//按住移动or压力值改变时的回调
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSArray *arrayTouch = [touches allObjects];
    UITouch *touch = (UITouch *)[arrayTouch lastObject];
    //红色背景的label显示压力值
    _forceLabel.text = [NSString stringWithFormat:@"压力%f",touch.force];
}

参考:

Getting Started with 3D Touch