你想知道的3D Touch開發全在這裏了

前言

iPhone 6s和iPhone 6s Plus爲多點觸摸界面帶來了強大的3D觸摸新維度。這項新技術能夠感知用戶按下顯示屏的深度,讓他們比以往任什麼時候候都更能使用你的應用程序和遊戲。更多關於3D Touch的介紹能夠參見這裏html

正文

接下來會介紹一下全部關於3D Touch開發的一些內容。ios

0.判斷3D Touch是否可用

先判斷設備是否支持3D Touch,這裏主要用到的類是:UITraitCollection。在iOS9以後,可使用該類判斷設備是否支持3D Touch,蘋果官方說明以下:git

3D Touch and Trait Collections

Starting in iOS 9, you can use this class to check whether the device on which your app is running supports 3D Touch. Read the value of the forceTouchCapability property on the trait collection for any object in your app with a trait environment. For information about trait environments, see UITraitEnvironment. For the possible values of the force touch capability property, see the UIForceTouchCapability enumeration.github

Because a user can turn off 3D Touch in Settings, check the value of the forceTouchCapability property in your implementation of the traitCollectionDidChange:method, and adjust your code paths according to the property’s value.web

主要是使用了forceTouchCapability屬性,該屬性的枚舉值包括:macos

//未知
UIForceTouchCapabilityUnknown = 0,
//不可用
UIForceTouchCapabilityUnavailable = 1,
//可用
UIForceTouchCapabilityAvailable = 2

用戶在使用APP的時候也有可能在設置中關閉3D Touch,這個時候能夠實現traitCollectionDidChange:代理方法去監聽是否改變:(在VC中實現UITraitEnvironment協議)api

#pragma mark - UITraitEnvironment
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    if (previousTraitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        [self showAlertWithStrig:@"3D Touch已關閉"];
    }else if (previousTraitCollection.forceTouchCapability == UIForceTouchCapabilityUnavailable) {
        [self showAlertWithStrig:@"3D Touch已打開"];
    }
}

這裏注意:拿到的traitcollection是previousTraitCollection瀏覽器

1.Home screen quick action API(主屏幕交互)

該API主要用於添加應用程序圖片的快捷方式,以預測並加速用戶與應用的互動。ruby

1.1.用例

Demo

1.2.代碼實例

兩種方法實現該特性,直接使用代碼開發,或者直接在Info.plist文件配置。微信

1.2.1.Static quick actions

直接在application:didFinishLaunchingWithOptions:方法中處理:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     
    NSMutableArray *shortCutItemArr = [NSMutableArray arrayWithCapacity:4];
    UIApplicationShortcutIcon *icon1 = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeSearch];
    UIApplicationShortcutItem *shortItem1 = [[UIApplicationShortcutItem alloc] initWithType:@"com.zhanggui.Demo.search" localizedTitle:@"搜索" localizedSubtitle:@"搜索想要的電影" icon:icon1 userInfo:nil];
    [shortCutItemArr addObject:shortItem1];
    [UIApplication sharedApplication].shortcutItems = shortCutItemArr;
    return YES;
}

設置shortcutItems便可。

1.2.2.Dynamic quick actions

直接使用Info.plist文件配置:

<array>
    <dict>
        <key>UIApplicationShortcutItemIconType</key>
        <string>UIApplicationShortcutIconTypeShare</string>
        <key>UIApplicationShortcutItemTitle</key>
        <string>取票碼</string>
        <key>UIApplicationShortcutItemType</key>
        <string>com.zhanggui.Demo.getTicket</string>
        <key>UIApplicationShortcutItemUserInfo</key>
        <dict>
            <key>key2</key>
            <string>value2</string>
        </dict>
    </dict>
</array>

關於key值的介紹,能夠參見Info.plist Keys and Values
處理點擊元素監聽:

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
    NSLog(@"%@",shortcutItem);
}

在AppDelegate中實現協議application:performActionForShortcutItem:completionHandler:方法便可。

1.3.核心類說明

UIApplicationShortcutItem:3D Touch彈框中每一條操做元素。
UIApplicationShortcutIcon:操做元素的icon。

1.3.1.UIApplicationShortcutItem
#if USE_UIKIT_PUBLIC_HEADERS || !__has_include(<UIKitCore/UIApplicationShortcutItem.h>)
//
//  UIApplicationShortcutItem.h
//  UIKit
//
//  Copyright © 2015-2018 Apple Inc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKitDefines.h>

NS_ASSUME_NONNULL_BEGIN

@class UIImage;

typedef NS_ENUM(NSInteger, UIApplicationShortcutIconType) {
    UIApplicationShortcutIconTypeCompose,
    UIApplicationShortcutIconTypePlay,
    UIApplicationShortcutIconTypePause,
    UIApplicationShortcutIconTypeAdd,
    UIApplicationShortcutIconTypeLocation,
    UIApplicationShortcutIconTypeSearch,
    UIApplicationShortcutIconTypeShare,
    UIApplicationShortcutIconTypeProhibit       NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeContact        NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeHome           NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeMarkLocation   NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeFavorite       NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeLove           NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeCloud          NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeInvitation     NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeConfirmation   NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeMail           NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeMessage        NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeDate           NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeTime           NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeCapturePhoto   NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeCaptureVideo   NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeTask           NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeTaskCompleted  NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeAlarm          NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeBookmark       NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeShuffle        NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeAudio          NS_ENUM_AVAILABLE_IOS(9_1),
    UIApplicationShortcutIconTypeUpdate         NS_ENUM_AVAILABLE_IOS(9_1)
} API_AVAILABLE(ios(9.0)) API_UNAVAILABLE(tvos) API_UNAVAILABLE(macos);

UIKIT_EXTERN API_AVAILABLE(ios(9.0)) API_UNAVAILABLE(tvos) API_UNAVAILABLE(macos)
@interface UIApplicationShortcutIcon : NSObject <NSCopying>

// Create an icon using a system-defined image.
+ (instancetype)iconWithType:(UIApplicationShortcutIconType)type;

// Create an icon from a custom image.
// The provided image named will be loaded from the app's bundle
// and will be masked to conform to the system-defined icon style.
+ (instancetype)iconWithTemplateImageName:(NSString *)templateImageName;

@end

UIKIT_EXTERN API_AVAILABLE(ios(9.0)) API_UNAVAILABLE(tvos) API_UNAVAILABLE(macos)
@interface UIApplicationShortcutItem : NSObject <NSCopying, NSMutableCopying>

- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithType:(NSString *)type localizedTitle:(NSString *)localizedTitle localizedSubtitle:(nullable NSString *)localizedSubtitle icon:(nullable UIApplicationShortcutIcon *)icon userInfo:(nullable NSDictionary<NSString *, id <NSSecureCoding>> *)userInfo NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithType:(NSString *)type localizedTitle:(NSString *)localizedTitle;

// An application-specific string that identifies the type of action to perform.
@property (nonatomic, copy, readonly) NSString *type;

// Properties controlling how the item should be displayed on the home screen.
@property (nonatomic, copy, readonly) NSString *localizedTitle;
@property (nullable, nonatomic, copy, readonly) NSString *localizedSubtitle;
@property (nullable, nonatomic, copy, readonly) UIApplicationShortcutIcon *icon;

// Application-specific information needed to perform the action.
// Will throw an exception if the NSDictionary is not plist-encodable.
@property (nullable, nonatomic, copy, readonly) NSDictionary<NSString *, id <NSSecureCoding>> *userInfo;

@end

UIKIT_EXTERN API_AVAILABLE(ios(9.0)) API_UNAVAILABLE(tvos) API_UNAVAILABLE(macos)
@interface UIMutableApplicationShortcutItem : UIApplicationShortcutItem

// An application-specific string that identifies the type of action to perform.
@property (nonatomic, copy) NSString *type;

// Properties controlling how the item should be displayed on the home screen.
@property (nonatomic, copy) NSString *localizedTitle;
@property (nullable, nonatomic, copy) NSString *localizedSubtitle;
@property (nullable, nonatomic, copy) UIApplicationShortcutIcon *icon;

// Application-specific information needed to perform the action.
// Will throw an exception if the NSDictionary is not plist-encodable.
@property (nullable, nonatomic, copy) NSDictionary<NSString *, id <NSSecureCoding>> *userInfo;

@end

NS_ASSUME_NONNULL_END

#else
#import <UIKitCore/UIApplicationShortcutItem.h>
#endif

經常使用方法:
建立一個UIApplicationShortcutItem:

- (instancetype)initWithType:(NSString *)type localizedTitle:(NSString *)localizedTitle localizedSubtitle:(nullable NSString *)localizedSubtitle icon:(nullable UIApplicationShortcutIcon *)icon userInfo:(nullable NSDictionary<NSString *, id <NSSecureCoding>> *)userInfo NS_DESIGNATED_INITIALIZER;
 
- (instancetype)initWithType:(NSString *)type localizedTitle:(NSString *)localizedTitle;

其中:

  • type表明:必傳,app定義的主屏幕快速操做類型,能夠用於肯定某元素點擊
  • localizedTitle:展現的title
  • localizedSubtitle:sub title
  • icon:該item左側或者右側的icon,類型爲UIApplicationShortcutIcon
  • userInfo:用戶自定義的一些信息
1.3.2.UIApplicationShortcutIcon

icon有兩種獲取方式:一種是使用系統自帶的類型,一種是用戶自定義(根據圖片名)。

1.3.2.1 系統自帶類型
// Create an icon using a system-defined image.
+ (instancetype)iconWithType:(UIApplicationShortcutIconType)type;

系統自帶類型包括如下幾種:

系統自帶icon類型

1.3.2.1 用戶自定義
// Create an icon from a custom image.
// The provided image named will be loaded from the app's bundle
// and will be masked to conform to the system-defined icon style.
+ (instancetype)iconWithTemplateImageName:(NSString *)templateImageName;

用戶自定義的圖片格式規定以下:

square, single color, and 35x35 points(正方形、單色、35*35大小)

若是圖片找不到,則展現爲原點。效果可本身測試一下。

1.4.使用方式

  1. 直接使用Info.plist文件進行配置
  2. 直接編寫代碼

當同時使用二者時,會進行疊加,而且Info.plist配置中的元素會優先於AppDelegate中配置的元素展現。

1.5.個數限制

常規狀況下,最多能夠自定義4個Home screen quick action。在APP未上線以前,能夠看到自定義的4個,多餘的將會被忽略。在APP上線以後,將會有一個系統自帶的item:分享 「APP名稱」。總共不超過5個。

1.6.使用場景

可以進行快捷操做的事件,好比微信的掃一掃,微信支付、個人電影票等。

2.UIKit peek and pop API(預覽和跳轉)

UIKit的peek和pop API容許開發者在維護用戶上下文的同時,在應用中提供對附加內容的輕鬆訪問。使用peek quick actions能夠爲應用的觸摸和按住操做提供按下的替換。
peek:當用戶點擊特定的view,會提供一個額外的預覽視圖。
pop:確認查看該內容,而且導航到該內容詳情。
在iOS9以及之後的SDK中,爲UIViewController提供了註冊3D Touch和取消註冊3D Touch的新方法,它們是:

// Registers a view controller to participate with 3D Touch preview (peek) and commit (pop).
- (id <UIViewControllerPreviewing>)registerForPreviewingWithDelegate:(id<UIViewControllerPreviewingDelegate>)delegate sourceView:(UIView *)sourceView NS_AVAILABLE_IOS(9_0);
- (void)unregisterForPreviewingWithContext:(id <UIViewControllerPreviewing>)previewing NS_AVAILABLE_IOS(9_0);

在註冊方法中,sourceView就是要添加3D Touch的view。調用該註冊方法的時候,它作了三件事:

  • 註冊調用該方法的控制器參與3D Touch的預覽(preview)和執行(commit)
  • 從接收方的視圖層級結構中,將sourceView指定爲響應強按壓的視圖
  • 指定委託對象,當用戶進行強按壓時依次請求peek和pop,該委託對象用於協調操做(vc實現了peek和pop代理方法)

You can designate more than one source view for a single registered view controller, but you cannot designate a single view as a source view more than once.

你能夠在一個vc中指定多個sourceView,可是不能同一個view指定爲sourceView屢次。
註冊方法返回的上下文對象的生命週期由系統管理。若是你須要指明取消註冊該vc,把該context對象傳給unregisterForPreviewingWithContext:。若是開發者不取消註冊,系統會在改VC釋放的時候自動取消註冊。
Demo中的註冊方法實現以下:

if ([self.imageView respondsToSelector:@selector(traitCollection)]) {
    if([self.traitCollection respondsToSelector:@selector(forceTouchCapability)]) {
        if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
            [self registerForPreviewingWithDelegate:(id)self sourceView:self.imageView];
        }
    }
}

註冊完成以後,須要實現UIViewControllerPreviewingDelegate,該代理主要有兩個方法:

- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    ImageViewController *imageVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ImageVC"];
    [self presentViewController:imageVC animated:YES completion:nil];
}
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
    ImageViewController *imageVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ImageVC"];
    imageVC.preferredContentSize = CGSizeMake(0.0, 300);
    return imageVC;
}

第一個方法用於處理commit操做,也就是確認操做,確認3D Touch執行操做。
第二個方法在用戶按下源視圖顯示peek時調用,實現此方法用以返回預覽視圖控制器。(這裏返回的是ImageViewController)。若是此處返回nil,將會禁用預覽。此處還會使用到previewingContext.sourceReact,該屬性主要是在sourceView座標系中,矩形響應用戶的3D觸摸,當矩形週會內容模糊時,矩形在視覺上保持清晰,具體可參見視頻: https://github.com/ScottZg/MarkDownResource/blob/feature/addrubyimagefile/3DTouch/sourcReact.MP4

2.1.快速操做

可使用該API進行快速操做需求開發,例如微信重壓聊天列表中的某個cell,就能夠彈出快速操做:再也不關注、刪除。這些快速操做很簡單:在預覽的VC中添加下面的代碼便可。實例代碼以下:

- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {
    NSMutableArray *arrItem = [NSMutableArray arrayWithCapacity:2];
    UIPreviewAction *cancel = [UIPreviewAction actionWithTitle:@"取消" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"cancel");
    }];
    UIPreviewAction *ok = [UIPreviewAction actionWithTitle:@"刪除" style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        self.imageView.image = nil;
    }];
    
    UIPreviewAction *select = [UIPreviewAction actionWithTitle:@"選中" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"selected");
    }];
//    組操做
    UIPreviewAction *add = [UIPreviewAction actionWithTitle:@"增長" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"增長");
    }];
    UIPreviewAction *update = [UIPreviewAction actionWithTitle:@"更新" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"更新");
    }];
    UIPreviewActionGroup *group = [UIPreviewActionGroup actionGroupWithTitle:@"更多操做" style:UIPreviewActionStyleDefault actions:@[add,update]];
    [arrItem addObject:cancel];
    [arrItem addObject:ok];
    [arrItem addObject:select];
    [arrItem addObject:group];
    return arrItem;
}

這裏主要實現了previewActionItems方法,用來設置預覽的Action元素,這裏涉及到的類有:

  • UIPreviewAction:預覽的Action,當用戶在支持3D Touch而且在peek視圖下向上滑動,便可看到這些Action。
  • UIPreviewActionItem:協議,包含了一個只讀的title。
  • UIPreviewActionGroup:操做組,能夠設置一個操做組進行操做,例如二次確認。
2.1.1.UIPreviewAction

具體的操做元素,包括title、類型以及事件處理。其中style有如下三種類型:

typedef NS_ENUM(NSInteger,UIPreviewActionStyle) {
    UIPreviewActionStyleDefault=0,  //默認
    UIPreviewActionStyleSelected,  //選中
    UIPreviewActionStyleDestructive,  //銷燬:紅色
} NS_ENUM_AVAILABLE_IOS(9_0);
2.1.2.UIPreviewActionItem

協議,包含了一個屬性title。表明操做action的title。

2.1.3.UIPreviewActionGroup

操做組,支持一個元素多個操做,具體能夠參見下面的小視頻:https://github.com/ScottZg/MarkDownResource/blob/feature/addrubyimagefile/3DTouch/group.MP4

3.Web view peek and pop API

在網頁中,對於網頁中的連接,peek和pop是默認支持的,能夠經過設置allowsLinkPreview進行開啓或關閉:
WKWebView:

/*! @abstract A Boolean value indicating whether link preview is allowed for any
 links inside this WKWebView.
 @discussion The default value is YES on Mac and iOS.
 */
@property (nonatomic) BOOL allowsLinkPreview API_AVAILABLE(macosx(10.11), ios(9.0));

UIWebView:

@property (nonatomic) BOOL allowsLinkPreview NS_AVAILABLE_IOS(9_0); // default is NO

默認狀況下使用蘋果自帶的瀏覽器打開,這樣就會跳出本身的應用。
嘗試本身對wkwebview進行註冊,而後本身設置peek和pop,發現無效。
可使用SFSafariViewController替代WebView。

SFSafariViewController使用presentViewController:animated:completion:方法展現。效果和push同樣。

4.UITouch force properties

UITouch類提供了兩個新的屬性來支持自定義實現3D Touch:

// Force of the touch, where 1.0 represents the force of an average touch
@property(nonatomic,readonly) CGFloat force NS_AVAILABLE_IOS(9_0);
// Maximum possible force with this input mechanism
@property(nonatomic,readonly) CGFloat maximumPossibleForce NS_AVAILABLE_IOS(9_0);

具體使用能夠參見Demo

參考文檔

  1. Adopting 3D Touch on iPhone
  2. https://developer.apple.com/ios/3d-touch/
  3. registerForPreviewingWithDelegate
相關文章
相關標籤/搜索