3D Touch 简单应用

今年苹果发布了 iPhone 6s 和 iPhone 6s Plus,其中最引人关注的更新便是加入了全新的触控方式——3D Touch。最近几天简单地研究了一下,跟大家分享一下我的一些经验。

UIApplicationShortcutItems


当你重按应用的图标时,会弹出类似这样的小菜单(以微信为例):


ShortcutItems

添加这样的快捷菜单主要有 静态动态 两种方法:

静态方法

参看 UIApplicationShortcutItems-苹果官方文档

ShortcutItems 变量说明

可以看到 UIApplicationShortcutItemTitleUIApplicationShortcutItemType 这两个变量是必须的。

我们在项目的 info.plist 文件中添加如下信息:

静态添加 `ShortcutItems`

运行结果:


动态方法

动态方法是在项目中添加代码:

UIApplicationShortcutItem *item1 = [[UIApplicationShortcutItem alloc] initWithType:@"one" localizedTitle:@"Title One" localizedSubtitle:@"Sub one" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypePlay] userInfo:nil];
UIApplicationShortcutItem *item2 = [[UIApplicationShortcutItem alloc] initWithType:@"two" localizedTitle:@"Title Two" localizedSubtitle:@"Sub two" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeHome] userInfo:nil];

[UIApplication sharedApplication].shortcutItems = @[item1, item2];

当该段代码在程序中被执行过一次后才会被添加到主屏幕的 ShortcutItems 菜单中。
运行结果:

注意: ShortcutItems 会优先加载静态方法添加的,然后加载动态方法添加的,并且同时只能拥有最多4个ShortcutItems。

选择 ShortcutItem 后的回调

AppDelegate 根据 shortcutItem.type 判断回调方法:

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

    if ([shortcutItem.type isEqualToString:@"one"]) {
        NSLog(@"Choose One");
        MyViewController *vc = [[MyViewController alloc] init];
        vc.title = @"One";
        vc.view.backgroundColor = [UIColor whiteColor];
        [self.window.rootViewController showViewController:vc sender:nil];
    } else if ([shortcutItem.type isEqualToString:@"two"]) {
        NSLog(@"Choose Two");
        MyViewController *vc = [[MyViewController alloc] init];
        vc.title = @"Two";
        vc.view.backgroundColor = [UIColor orangeColor];
        [self.window.rootViewController showViewController:vc sender:nil];
    }    
}

按压力度感应


在9.0后 UITouch 新增这样两个属性:

9.0新增touch属性

我们创建一个继承于 UIView 的自定义View,这里我们首先要判断一下设备是否支持3D Touch:

- (BOOL)check3DTouch {
    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        return YES;
    } else {
        return NO;
    }
}

然后在 touchesMoved 中调用方法:

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    if ([self check3DTouch]) {
        UITouch *touch = [touches anyObject];
        self.backgroundColor = [UIColor colorWithRed:touch.force / touch.maximumPossibleForce  green:0.0f blue:0.0f alpha:1.0f];
    } else {
        NSLog(@"CAN NOT USE 3D TOUCH!");
    }
}

这样我们我创建了一个可以根据按压力度改变颜色的View。

Peek & Pop


Peek和Pop:

Peek是指重按一下后出现的预览,Pop是在Peek后进一步按压后进入预览的视图控制器。
首先遵循代理 <UIViewControllerPreviewingDelegate>
然后监测设备是否支持3D Touch,若支持则对需要响应Peek操作的视图进行注册:

- (void)check3DTouch {
    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        [self registerForPreviewingWithDelegate:self sourceView:_label];
    }
}

Peek的代理方法

- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
      MyViewController *vc = [[MyViewController alloc] init];
      vc.title = @"Hello";
      vc.view.backgroundColor = [UIColor cyanColor];
      return vc;
}

其实就是返回一个视图控制器实例,但是看网上说这个方法会被多次调用,我实际测试有时会调用多次,有时只调用一次,还是不太清楚具体调用情况,有知道的朋友欢迎交流一下。为了保险起见,还是建议写成下面的形式:

- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
    if ([self.presentedViewController isKindOfClass:[MyViewController class]]) {
        return nil;
    } else {
        MyViewController *vc = [[MyViewController alloc] init];
        vc.title = @"Hello";
        vc.view.backgroundColor = [UIColor cyanColor];
        return vc;
    }
}

至于Pop的方法就更简单了,直接调用下面的方法:
Pop的代理方法

- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    [self showViewController:viewControllerToCommit sender:self];
}

PreviewAction Items

有时在进入Peek但未Pop的时候,我们可以向上滑动选 PreviewAction Items


PreviewAction Items

PreviewAction Items 是在被预览的viewController下面添加下面方法实现的:

- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {
    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"Default" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        
    }];
    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"Selected" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        
    }];
    UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"Destructive" style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        
    }];
    NSArray *actions = @[action1, action2, action3];
    
    UIPreviewActionGroup *group = [UIPreviewActionGroup actionGroupWithTitle:@"Actions Group" style:UIPreviewActionStyleDefault actions:actions];
    
    UIPreviewAction *action4 = [UIPreviewAction actionWithTitle:@"Single Action" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        
    }];

    NSArray *array = @[group, action4];

    return array;
}

通过返回 UIPreviewActionUIPreviewActionGroup 组成的数组实现。

一个viewController下注册多个视图控件

前面说到如果要让视图控件响应Peek操作需要对其进行注册,但是如果一个viewController中有多个控件需要响应Peek并且可能不知道何时会出现的时候(譬如添加了一个tableView后,需要每一个单独的cell独立响应一个Peek操作),是不可能一个一个注册的,这个时候我们可以直接将- (void)check3DTouch 中的代码改成:

- (void)check3DTouch {
    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        [self registerForPreviewingWithDelegate:self sourceView:self.view];
    }
}

我们直接注册整个view,根据peek代理方法中的属性location 判断响应的UI控件

- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {

    if (CGRectContainsPoint(_tableView.frame, location)) {
        if ([self.presentedViewController isKindOfClass:[DisplayViewController class]]) {
            return nil;
        } else {
            location = [self.view convertPoint:location toView:_tableView];
            NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:location];
            NSLog(@"%@", indexPath);
            DisplayViewController *displayVC = [[DisplayViewController alloc] init];
            displayVC.title = [_tableView cellForRowAtIndexPath:indexPath].textLabel.text;
            displayVC.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 256.0
                                                             green:arc4random() % 256 / 256.0
                                                              blue:arc4random() % 256 / 256.0
                                                             alpha:1.0];
            
            // peek预览窗口大小
            displayVC.preferredContentSize = CGSizeMake(0.0, 100 * indexPath.row);
            
            // 进入peek前不被虚化的rect
            previewingContext.sourceRect = [self.view convertRect:[_tableView cellForRowAtIndexPath:indexPath].frame fromView:_tableView];
            
            return displayVC;
        }
    }
    
    
    if ([self.presentedViewController isKindOfClass:[MyViewController class]]) {
        return nil;
    } else {
        if (CGRectContainsPoint(_label.frame, location)) {
            MyViewController *vc = [[MyViewController alloc] init];
            vc.title = @"Hello";
            vc.view.backgroundColor = [UIColor cyanColor];
            NSLog(@"New ViewController.");
            return vc;
        }
    }
    
    return nil;
}

3D Touch 小应用 —— 压力感应画板


这段是引用了 crazypoo/TouchNewAPI 的代码

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    _touchPoint = [touch locationInView:_drawBoard];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:_drawBoard];
    
    UIGraphicsBeginImageContext(_drawBoard.frame.size);
    [_drawBoard.image drawInRect:_drawBoard.frame];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    
    float lineWidth = 10.0f;
    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        lineWidth *= touch.force;
    }
    
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), lineWidth);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), _touchPoint.x, _touchPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    _drawBoard.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    _touchPoint = currentPoint;
}

以上是我的一点浅薄的心得,本文中所有代码都已经上传至 kisekied/3DTouchDemo 欢迎大家交流讨论。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • 1.什么是3D Touch? 3D Touch属于一种人机交互的一种方式,具体点用户与手机屏幕的一种交互方式。在3...
    alpha_feng阅读 741评论 0 3
  • 前言 关于这篇文章 由于iPhone 6S发布不到一年的时间,很多新特性、新技术还未普遍,不管是3D Touch的...
    Tangentw阅读 4,444评论 8 18
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,943评论 4 60
  • 苹果6s已经问世很久了,相信大家对3D Touch功能也不陌生了,个人非常喜欢那个重按的手感.之前一直感觉这个新功...
    和影子玩拳击阅读 328评论 0 2
  • 蕾是公司有名的培训师,在培训时,个人演讲魅力十足,大家都认为她是天生的演讲者,而蕾自己和我们分享了她的心得。 蕾说...
    盆叔阅读 268评论 0 1