前言
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, seeUITraitEnvironment
. For the possible values of the force touch capability property, see theUIForceTouchCapability
enumeration.Because a user can turn off 3D Touch in Settings, check the value of the
forceTouchCapability
property in your implementation of thetraitCollectionDidChange:
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.用例
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:(UI