iOS 实现3DTouch的方法
2019-03-28 本文已影响166人
枫developer
好久没有更新简书了,真是很不好意思。未来一个月可能还是不能及时更新,还请见谅。
今天因为时间有限,给大家介绍一个挺有用,而且十分简单的功能:3DTouch。
3DTouch.jpeg
如图,大家在使用iPhone6S以上机型的时候一定用到过这个功能。而且它的实现原理很简单。这里给大家介绍两种:
1.代码实现:
-(void)setup3DTouch {
/// 这里的字符串的是图片名称,就是显示在3DTouch上的图片
UIApplicationShortcutIcon *itemIconCart = [UIApplicationShortcutIcon iconWithTemplateImageName:@"cart"];
/// 这里的中文名是名称。相对应的@“cart”起的是标识作用,相当于tag,来告诉我们用户点击的按钮
UIApplicationShortcutItem *itemCart = [[UIApplicationShortcutItem alloc] initWithType:@"cart" localizedTitle:@"购物车" localizedSubtitle:@"" icon:itemIconCart userInfo:nil];
UIApplicationShortcutIcon *itemIconDesigner = [UIApplicationShortcutIcon iconWithTemplateImageName:@"designer"];
UIApplicationShortcutItem *itemDesigner = [[UIApplicationShortcutItem alloc] initWithType:@"designer" localizedTitle:@"品牌" localizedSubtitle:@"" icon:itemIconDesigner userInfo:nil];
UIApplicationShortcutIcon *itemIconSearch = [UIApplicationShortcutIcon iconWithTemplateImageName:@"search"];
UIApplicationShortcutItem *itemSearch = [[UIApplicationShortcutItem alloc] initWithType:@"search" localizedTitle:@"搜索" localizedSubtitle:@"" icon:itemIconSearch userInfo:nil];
NSMutableArray *arrShortcutItem = (NSMutableArray *)[UIApplication sharedApplication].shortcutItems;
[arrShortcutItem addObjectsFromArray:@[itemCart, itemDesigner, itemSearch]];
/// 将需要的3DTouch按钮放入集合之中
[UIApplication sharedApplication].shortcutItems = arrShortcutItem;
}
很简单,最终的效果就是第一张图片。
2.plist完成:
plist.jpeg
UIApplicationShortcutItemIconFile
3DTouch按钮的图片名称
UIApplicationShortcutItemTitle
按钮显示名称
UIApplicationShortcutItemType
唯一标识符,就是相当于tag的作用
UIApplicationShortcutItemSubtitle
快捷可选项的子标题
UIApplicationShortcutItemIconType
快捷可选项的图标
UIApplicationShortcutItemUserInfo
快捷可选项的附加信息
好了,介绍完如何显示,接下来我们再介绍用户点击之后我们需要怎么操作。其实简单,在AppDelegate中,有一个方法:
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
所有的操作只需要在这个方法中实现就可以了
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
NSLog(@"name:%@\ntype:%@", shortcutItem.localizedTitle, shortcutItem.type);
}
接下来,我点击“搜索”,看看会有什么打印出来。
搜索.jpeg
所以大家只需要在方法之中将对应的逻辑完成就可以了。很简单吧。
喜欢的朋友可以收藏一下哈。😘