你想知道的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, 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:(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;
系统自带类型包括以下几种:
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.使用方式
- 直接使用info.plist文件进行配置
- 直接编写代码
当同时使用两者时,会进行叠加,并且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。