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


前言

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

正文

接下來會介紹一下所有關於3D Touch開發的一些內容。

0.判斷3D Touch是否可用

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

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.

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.

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

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

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

#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主要用於添加應用程序圖片的快捷方式,以預測並加速用戶與應用的互動。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM