iOS 3D Touch 这个技能不白学

随着iOS9和6S的到来,3D Touch已经被人们逐渐熟悉和使用,所以本篇主要讲讲这个新技能如何get,以及如何做的更出色。

首先可以先判断该设备是否支持3D touch:
[code lang=”Objective-C”]if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
// UIViewControllerPreviewingDelegate
[self registerForPreviewingWithDelegate:self sourceView:_imageView];
}[/code]
然后实现delegate:
[code lang=”Objective-C”]- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
    UIButton *imageView = (UIButton *)[previewingContext sourceView];
    [previewingContext setSourceRect:imageView.bounds];

    POPViewController *p = [[POPViewController alloc] init];
    p.preferredContentSize = CGSizeMake(0, 100);
    p.view.backgroundColor = [UIColor blackColor];
    return p;
}[/code]
[code lang=”Objective-C”]- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
{
    [self presentViewController:viewControllerToCommit animated:YES completion:nil];
}[/code]
这样可以简单完成一个3D touch Demo,想要实现上拉展示文字可以这样做:
[code lang=”Objective-C”]- (NSArray *)preActions
{
    if (!_preActions) {   
    UIPreviewAction *action0 = [UIPreviewAction actionWithTitle:@”test” style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
    }];

    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@”test1″ style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {

    }];

    UIPreviewActionGroup *actionGroup = [UIPreviewActionGroup actionGroupWithTitle:@”actionGroup” style:UIPreviewActionStyleSelected actions:@[action0, action1]];

    _preActions = @[action0, action1, actionGroup];
    }

    return _preActions;
}
[/code]
[code lang=”Objective-C”]
// 设置控制器在弹窗时候,下面输出的数组- (NSArray<id<UIPreviewActionItem>> *)previewActionItems
{
    return self.preActions;
}[/code]
以上就是粗略的实现了内部3D touch 的功能

WebView只需要添加
[code lang=”Objective-C”]webView.allowsLinkPreview = YES[/code]
即可实现3D touch 的功能
[code lang=”Objective-C”]UITouch *touch = touches.anyObject;[/code]
touch.force这个可以看到用的按压的力度做出相应的判断