初學3D Touch

引言

With iOS 9, new iPhone models add a third dimension to the user interface.html

  • A user can now press your Home screen icon to immediately access functionality provided by your app.
  • Within your app, a user can now press views to see previews of additional content and gain accelerated access to features.

模擬器實現3D Touch功能

一、插件安裝

插件下載地址:
https://github.com/DeskConnect/SBShortcutMenuSimulatorios

  • 下載插件到本地(在terminal操做):
    git clone https://github.com/DeskConnect/SBShortcutMenuSimulator.git

     
  • 安裝插件:
    cd SBShortcutMenuSimulator
    make

     

二、插件使用

  • 啓動插件git

    xcrun simctl spawn booted launchctl debug system/com.apple.SpringBoard --environment DYLD_INSERT_LIBRARIES=$PWD/SBShortcutMenuSimulator.dylib xcrun simctl spawn booted launchctl stop com.apple.SpringBoard

    注意:若是運行過程當中出現:No devices are booted. 是由於你的模擬器沒有啓動,這時候啓動你的模擬器便可。github

  • 預覽效果web

    echo 'com.apple.mobilecal' | nc 127.0.0.1 8000


    注意:
    一、'com.apple.mobilecal'是應用的Bundle ID,若是你要測試本身的應用的3D Touch效果,將該字段換成本身應用的Bundle ID。上面的示例應用是系統日曆。
    二、若是出現SpringBorad意外退出,多是你的模擬器高於iOS9.1,能夠嘗試下載iOS9.1或iOS9.0的模擬器而後從新以上「插件使用」操做。bash

檢測是否支持3D Touch

  • 在UIViewController生命週期的viewWillAppear中作判斷:
    -(void)viewWillAppear:(BOOL)animated{
      [super viewWillAppear:animated];
      if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) { //3D Touch可用  } else{ //3D Touch不可用  } }

     

    UIForceTouchCapability是個枚舉
    @property (nonatomic, readonly) UIForceTouchCapability forceTouchCapability NS_AVAILABLE_IOS(9_0);
    
    
    typedef NS_ENUM(NSInteger, UIForceTouchCapability) {
      UIForceTouchCapabilityUnknown = 0,        //3D Touch檢測失敗
      UIForceTouchCapabilityUnavailable = 1,    //3D Touch不可用
      UIForceTouchCapabilityAvailable = 2       //3D Touch可用
    };

     

  • 也能夠經過如下方法實現判斷,當界面環境發生改變時會調用該方法:
    -(void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
      if (previousTraitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) { NSLog(@"3D Touch可用"); } else{ NSLog(@"3D Touch不可用"); } }

     

3D Touch開發

iOS9提供了四類API(Home Screen Quick Action、UIKit Peek & Pop 、WebView Peek & Pop 和UITouch Force Properties)用於操做3D Touch(Pressure Sensitivity 、 Peek and Pop 和 Quick Actions)。app

一、Home Screen Quick Actions

  用力按壓主屏幕的應用Icon,能夠經過3D Touch呼出一個快捷菜單,點擊快速進入相關功能模塊。ide

  
 
  


  其中系統自帶的圖片有如下類型:測試

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)
} NS_ENUM_AVAILABLE_IOS(9_0) __TVOS_PROHIBITED;

 

建立Quick Action有兩種方式:靜態和動態
  • 靜態建立
    靜態建立只需在Info.plist上添加相關功能設置:

    也能夠右擊Info.plist -> Open As -> Source Code,輸入:
    <key>UIApplicationShortcutItems</key>
      <array>
          <dict>
              <key>UIApplicationShortcutItemIconType</key>
              <string>UIApplicationShortcutIconTypeSearch</string>
              <key>UIApplicationShortcutItemSubtitle</key>
              <string>搜索好友</string>
              <key>UIApplicationShortcutItemTitle</key>
              <string>搜索</string>
              <key>UIApplicationShortcutItemType</key>
              <string>1</string>
              <key>UIApplicationShortcutItemUserInfo</key>
              <dict/>
          </dict>
          <dict>
              <key>UIApplicationShortcutItemIconType</key>
              <string>UIApplicationShortcutIconTypeAdd</string>
              <key>UIApplicationShortcutItemSubtitle</key>
              <string>添加好友</string>
              <key>UIApplicationShortcutItemTitle</key>
              <string>添加</string>
              <key>UIApplicationShortcutItemType</key>
              <string>2</string>
              <key>UIApplicationShortcutItemUserInfo</key>
              <dict/>
          </dict>
      </array>

     

  • 動態建立
    代碼建立3D Touch的item:
    UIApplicationShortcutItem *item1 = [[UIApplicationShortcutItem alloc] initWithType:@"3" localizedTitle:@"掃一掃"];
      UIApplicationShortcutIcon *icon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"3DSearch"]; UIApplicationShortcutItem *item2 = [[UIApplicationShortcutItem alloc] initWithType:@"4" localizedTitle:@"設置" localizedSubtitle:nil icon:icon userInfo:nil]; [UIApplication sharedApplication].shortcutItems = @[item1,item2];

     

    建立方法:
    -(instancetype)initWithType:(NSString *)type localizedTitle:(NSString *)localizedTitle localizedSubtitle:(nullable NSString *)localizedSubtitle icon:(nullable UIApplicationShortcutIcon *)icon userInfo:(nullable NSDictionary *)userInfo NS_DESIGNATED_INITIALIZER;
    -(instancetype)initWithType:(NSString *)type localizedTitle:(NSString *)localizedTitle;

     

    設置圖片方法:
    +(instancetype)iconWithType:(UIApplicationShortcutIconType)type;
    +(instancetype)iconWithTemplateImageName:(NSString *)templateImageName;

     


  注意:
  (1)系統限制每一個App最多可以顯示4個Action Item,其中包括靜態方式和動態方式進行建立的,超過個數不顯示。
  (2)若是靜態和動態方式同時使用的時候,給UIApplication的shortcutItems賦值的時候不會覆蓋靜態建立的items。
  (3)動態建立的方式只有在程序第一次啓動以後纔會顯示。
  (4)若是你要顯示系統圖片時,info.plist中不要添加UIApplicationShortcutItemIconFile屬性,由於當UIApplicationShortcutItemIconFile和UIApplicationShortcutItemIconType同時存在時,會優先使用UIApplicationShortcutItemIconFile設置的圖片。ui

  (5)Quick Actions顯示的icon在左邊或者右邊,這個是跟你的app 放在你手機的位置有關係,這個iOS會自動處理掉。

點擊Home Screen Quick Actions的相應回調
  • iOS9新增如下方法實現點擊 Home Screen Quick Action的相應回調,咱們能夠經過shortcutItem的type或者localizedTitle屬性(由於這兩個屬性時必須設置的)判斷點擊了哪一個item:
    -(void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void(^)(BOOL succeeded))completionHandler {
      NSInteger index = shortcutItem.type.integerValue; switch (index) { case 1: NSLog(@"搜索"); break; case 2: NSLog(@"添加"); break; case 3: NSLog(@"掃一掃"); break; case 4: NSLog(@"設置"); break; default: break; } }

     

  • 還能夠經過入口方法裏面進行判斷(該方法只會在程序從未啓動到啓動過程當中纔會被調用):

    -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
      if (launchOptions) { UIApplicationShortcutItem *item = [launchOptions valueForKey:UIApplicationLaunchOptionsShortcutItemKey]; NSInteger index = item.type.integerValue; switch (index) { case 1: NSLog(@"搜索"); break; case 2: NSLog(@"添加"); break; case 3: NSLog(@"掃一掃"); break; case 4: NSLog(@"設置"); break; default: break; } } return YES; }

     

二、Peek & Pop

A peek :
Appears while a user presses on an item that supports peek and disappears when the user’s finger lifts
Opens a detailed view of the item—called a pop—when users press a little deeper on the peek view
Can provide quick actions related to the item when users swipe up within the peek view

                       
 
 
UIKit Peek & Pop
  • 給ViewController上的view註冊3D Touch(先判斷設備是否支持3D Touch)

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

     

  • 新建一個新的UIViewController名爲:ContentViewController,以便以後peek時顯示該ContentViewController,在ContentViewController中重寫如下方法實現Quick actions:

    -(NSArray<id<UIPreviewActionItem>> *)previewActionItems{
      UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"action1" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) { NSLog(@"action1"); }]; UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"action2" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) { NSLog(@"action2"); }]; NSArray *actions = @[action1,action2]; UIPreviewActionGroup *group1 = [UIPreviewActionGroup actionGroupWithTitle:@"Action Group" style:UIPreviewActionStyleDefault actions:actions]; NSArray *array = @[group1]; return array; }

     

    注意:
    一、該方法不是必需要重寫,根據本身的需求而定。
    二、這裏是把兩個action放在了一個組裏顯示,也能夠直接顯示兩個action。

  • ViewController遵循UIViewControllerPreviewingDelegate協議:

    //UIViewControllerPreviewingDelegate
    //稍微重按調用該方法:(peek)
    -(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location{
      //防止重複加入
      if ([self.presentedViewController isKindOfClass:[ContentViewController class]]){ return nil; } else { ContentViewController *contentVC = [[ContentViewController alloc] init]; return contentVC; } } //加劇按壓調用該方法:(pop) -(void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit{ //跳轉到某個ViewController ContentViewController *contentVC = [[ContentViewController alloc] init]; [self.navigationController pushViewController : contentVC animated:YES]; }

     

  • 效果圖:
                   
     

                   
WebKit Peek & Pop

  WebKit Peek & Pop 的操做和UIKit差很少,只是顯示的是Web網頁。
  顯示網頁有三種方法:
  一、openUrl離開應用進入safari打開網頁
  二、UIWebView或者WKWebView自定義視圖在應用內打開網頁
  三、在iOS9.0後新增SFSafariViewController類,用於顯示web網頁。並經過SFSafariViewControllerDelegate的如下方法實現回到應用操做。

-(void)safariViewControllerDidFinish:(SFSafariViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

 

  注意:
  一、方法1不能實現3D Touch。
  二、使用方法2實現3D Touch時,要設置屬性 allowsLinkPreview 爲Yes(默認是NO)。

參考文檔

     http://pingguohe.net/2015/10/12/3D-Touch-2.html
     http://www.devzeng.com/blog/ios9-3d-touch.html

相關文章
相關標籤/搜索