iOS 3D Touch超详细入门(附带demo示例代码)

点击上方“iOS开发”,选择“置顶公众号”

关键时刻,第一时间送达!

iOS 3D Touch超详细入门(附带demo示例代码)

iOS 3D Touch超详细入门(附带demo示例代码)


一、简介


3D Touch是指:通过对屏幕施加不同程度的压力来访问附加功能。应用可以通过显示菜单、展示其他内容和播放动画等形式来表现3D Touch,该功能从6s及其以上机型开始得到支持。


3D Touch的主要体现形式有三种:


  1. 主屏交互(Home Screen Interaction)

  2. 预览和跳转(Peek and Pop)

  3. LivePhoto


今天主要介绍前两种,第三种涉及到相册资源,有时间会将其作为一个独立的专题进行讲解。文末会附上GitHub地址。


二、提纲


1. 主屏交互(Home Screen Interaction)


  • 静态添加快捷操作(Static quick actions)

  • 动态添加快捷操作(Dynamic quick actions)


2. 预览和跳转(Peek and Pop)


  • Peek

    ①注册3D Touch

    ②通过代理实现功能


  • pop

    ①通过代理实现功能


三、实现


1.主屏操作


3D Touch在主屏交互的表现形式:当用户点击APP的同时并施加一定压力的时候,程序会在适当的位置展示出一个菜单选项列表。操作效果如下图所示:


iOS 3D Touch超详细入门(附带demo示例代码)


1.1.静态快捷操作


①通过静态的方式添加快捷操作:这种方式主要是在项目的Info.plist文件中添加相关的属性。


第一种在Info.plist文件添加方法:


iOS 3D Touch超详细入门(附带demo示例代码)


第二种在Info.plist文件添加方法:

1.右键Info.plist -->Open As ->Source Code;


iOS 3D Touch超详细入门(附带demo示例代码)


2.在文件中添加以下代码:


<key>UIApplicationShortcutItems</key>

    <array>

        <dict>

            <key>UIApplicationShortcutItemIconType</key>

            <string>UIApplicationShortcutIconTypeShare</string>

            <key>UIApplicationShortcutItemTitle</key>

            <string>分享“DM3DTouch”</string>

            <key>UIApplicationShortcutItemType</key>

            <string>cn.damon.DM3DTouchDemo.openShare</string>

            <key>UIApplicationShortcutItemUserInfo</key>

            <dict>

                <key>key2</key>

                <string>value2</string>

            </dict>

        </dict>

        <dict>

            <key>UIApplicationShortcutItemIconFile</key>

            <string>favorite</string>

            <key>UIApplicationShortcutItemTitle</key>

            <string>收藏</string>

            <key>UIApplicationShortcutItemType</key>

            <string>cn.damon.DM3DTouchDemo.openfavorites</string>

            <key>UIApplicationShortcutItemUserInfo</key>

            <dict>

                <key>key1</key>

                <string>value1</string>

            </dict>

        </dict>

    </array>


1.2.动态快捷操作


①通过动态的方式添加快捷操作:这种方式主要通过代码的形式把shortcutItems对象数组传递给UIApplication单例对象。我们可以在APP启动方法:


-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions


或者在windows.rootViewController的viewDidLoad方法里面添加我们的代码。

代码示例如下:


    NSMutableArray *arrShortcutItem = (NSMutableArray *)[UIApplication sharedApplication].shortcutItems;

    

    UIApplicationShortcutItem *shoreItem1 = [[UIApplicationShortcutItem alloc] initWithType:@"cn.damon.DM3DTouchDemo.openSearch" localizedTitle:@"搜索" localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeSearch] userInfo:nil];

    [arrShortcutItem addObject:shoreItem1];

    

    UIApplicationShortcutItem *shoreItem2 = [[UIApplicationShortcutItem alloc] initWithType:@"cn.damon.DM3DTouchDemo.openCompose" localizedTitle:@"新消息" localizedSubtitle:@"" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeCompose] userInfo:nil];

    [arrShortcutItem addObject:shoreItem2];

    

    [UIApplication sharedApplication].shortcutItems = arrShortcutItem;


附:参数对象说明


UIApplicationShortcutItem:可以看作是3D Touch点击后,弹出菜单每行对应的模型,一行对应一个UIApplicationShortcutItem对象。


实例化方法:


- (instancetype)initWithType:(NSString *)type localizedTitle:(NSString *)localizedTitle localizedSubtitle:(nullable NSString *)localizedSubtitle icon:(nullable UIApplicationShortcutIcon *)icon userInfo:(nullable NSDictionary *)userInfo:


type:对应UIApplicationShortcutItem对象的唯一标识符。

localizedTitle:对应UIApplicationShortcutItem对象的主标题。

localizedSubtitle:对应UIApplicationShortcutItem对象的副标题。

icon:对应要显示的图标,有两种图标:


①系统定义的类型,代码如下:


+ (instancetype)iconWithType:(UIApplicationShortcutIconType)type;


②用户自定义的类型,代码如下:


+ (instancetype)iconWithTemplateImageName:(NSString *)templateImageName;


要注意的是,如果通过第二种自定义方式创建图标,必须使用指定格式的图片,不然显示出来的是一片黑色。开发文档规定格式如下:


Icons should be square, single color, and 35x35 points


图片必须是正方形、单色并且尺寸是35*35像素的图片。(点击下载模板)

userInfo:主要是用来提供APP的版本信息。


如果同时使用静态和动态的方法添加,其添加的先后顺序是:先添加静态ShortcutItem对象,如果静态ShortcutItem对象不足4个,则继续添加动态ShortcutItem对象。官方文档提及到最多只能添加4个ShortcutItem对象,但是有的APP却能添加5个,有办法添加5个的欢迎留言讨论。


1.3.点击菜单选项进入APP的监听


当添加完ShortcutItem对象,我们的下一步任务就是监听用户点击哪一个选项进入到程序。我们只需要在APPDelegate中实现代理方法,如下:


- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {


    //不管APP在后台还是进程被杀死,只要通过主屏快捷操作进来的,都会调用这个方法

    NSLog(@"name:%@ type:%@", shortcutItem.localizedTitle, shortcutItem.type);    

}


我们可以通过shortcutItem对象获取到唯一标识符,只需要判断标识符就可以处理我们的逻辑任务了。


2.Peek and Pop


Peek and Pop主要是通过3D Touch,使用户可以在当前视图预览页面、链接或者文件。如果当前页面控制器注册了3D Touch,我们只需要点击相应的内容并施加一点压力,就能使当前内容高亮,并且其他内容进入一个模糊虚化的状态;当我们再施加一点压力,就能预览当前内容对应的页面;如果需要进入到该内容对应的页面,我们只需要稍微再施加一点压力直至预览视图放大到全屏,就可以跳转到其对应的页面。另外,如果我们在预览页面的同时,往上拖拽就可以显示出一个类似UIActionsheet界面的快捷操作菜单。以上所述效果如下:


iOS 3D Touch超详细入门(附带demo示例代码)


我们通过demo来对Peek and Pop进行实例分析,以下是该demo大致逻辑、功能说明:


iOS 3D Touch超详细入门(附带demo示例代码)


1.导航控制器的根控制器是VC1,通过点击VC1中tableView第X行,跳转到VC2。其中,VC2中有一个方法是把数据源的第X个元素替换成字符串【replace item】;

2.通过使用3D Touch,在VC1中实现快速预览的功能;

3.使用3D Touch,在VC1中跳转进入到VC2;

4.通过快捷菜单中的【替换该元素】选项,替换数据源中的第X个元素


2.1.实现VC1快速预览VC2的功能(Peek)


①要使用3D Touch,先向要响应3D Touch功能的视图控制器注册3D Touch,并指定接收手势的源视图。毫无疑问,要响应的视图是TableView中的Cell。我们在Cell的初始化方法中加入以下代码:


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusedId];

    

    if (!cell) {

        

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedId];

    }

    

    cell.contentView.backgroundColor = [UIColor grayColor];

    

    NSString *str = [NSString stringWithFormat:@"row [%@]", self.arrData[indexPath.row]];

    

    cell.textLabel.text = str;

    

    //注册3D Touch

    /**


     从iOS9开始,我们可以通过这个类来判断运行程序对应的设备是否支持3D Touch功能。


     UIForceTouchCapabilityUnknown = 0,     //未知

     UIForceTouchCapabilityUnavailable = 1, //不可用

     UIForceTouchCapabilityAvailable = 2    //可用

     */

    if ([self respondsToSelector:@selector(traitCollection)]) {

        

        if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)]) {

            

            if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {

                

                [self registerForPreviewingWithDelegate:(id)self sourceView:cell];

            }

        }

    }

    

    return cell;

}


因为只有在6s及其以上的设备才支持3D Touch,我们可以通过UITraitCollection这个类的UITraitEnvironment协议属性来判断设备是否支持3D Touch。


UITraitCollection是UIViewController所遵守的其中一个协议,不仅包含了UI界面环境特征,而且包含了3D Touch的特征描述。


②在VC1中实现UIViewControllerPreviewingDelegate代理,监听3D Touch手势的触发,示例代码如下:


- (nullable UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location NS_AVAILABLE_IOS(9_0) {


    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[previewingContext sourceView]];

    NSString *str = [NSString stringWithFormat:@"%@",self.arrData[indexPath.row]];

    

    //创建要预览的控制器

    DMPresentationViewController *presentationVC = [[DMPresentationViewController alloc] init];

    presentationVC.arrData = (NSMutableArray *)self.arrData;

    presentationVC.index = indexPath.row;

    presentationVC.strInfo = str;

    

    //指定当前上下文视图Rect

    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300);

    previewingContext.sourceRect = rect;


    return presentationVC;

}


2.2.实现从VC1跳转到VC2的功能(Pop)


要从VC1的快速预览视图跳转进入到VC2,我们需要在VC1中实现以下代理方法:


- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit NS_AVAILABLE_IOS(9_0) {


    [self showViewController:viewControllerToCommit sender:self];

}


2.3.快捷功能菜单的生成


如果我们需要在VC1快速预览视图出现时,向上拖拽得到一个快捷功能菜单,需要在VC2中实现以下代理方法:


- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {

    

    NSMutableArray *arrItem = [NSMutableArray array];

    

    UIPreviewAction *previewAction0 = [UIPreviewAction actionWithTitle:@"取消" style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {

        

        NSLog(@"didClickCancel");

    }];

    

    UIPreviewAction *previewAction1 = [UIPreviewAction actionWithTitle:@"替换该元素" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {

        

        //把下标为index的元素替换成preview

        [self replaceItem];

        

    }];

    

    [arrItem addObjectsFromArray:@[previewAction0 ,previewAction1]];

    

    return arrItem;

}


实现了这个代理,我们就可以在VC1中快速预览往上拖拽得到一个快捷功能菜单。而且,我们不需要进入VC2,直接通过点击快捷菜单的【替换该元素】这个选项,就能调用VC2替换元素的方法。应用场景:iPhone在短信列表页面,通过快捷功能菜单快速回短信。


至此,3D Touch就介绍完毕了。由于技术有限,加之时间匆忙,难免会存在纰漏,欢迎指正。转载请注明出处,万分感谢。


demon:https://github.com/DamonMok/DM3D-Touch-Demo(粘贴下载)


iOS 3D Touch超详细入门(附带demo示例代码)

  • 作者:DamonMok

  • 链接:http://www.jianshu.com/p/d472c6350a1a

  • 來源:简书

  • iOS开发整理发布,转载请联系作者授权

iOS 3D Touch超详细入门(附带demo示例代码)

iOS 3D Touch超详细入门(附带demo示例代码)【点击成为安卓大神】