上一篇博客说了,如何在创建以及响应ApplicationShortcutItem的方法,那么现在再来应用一下如何响应Peek、Pop操作,什么叫Peek操作呢,就是说当稍微重按得时候会出现一个预览视图,在此时可以上划出现快捷按钮,再按一下会弹到详细视图。
Demo:https://github.com/YRunIntoLove/3DTouchTest
对于Peek以及Pop操作,楼主也感谢下面的博客
首先为了能快速构建Demo,楼主用StoryBoard来创建控制器ViewController,以UITableView为例,如下
在此之上,是否支持3D Touch以及是否开启3D Touch方法如下
/**
* 检测是否支持3D Touch
*
* @return YES || NO
*/
- (BOOL)Check3DTouch
{
if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)
{
return YES;
}
return NO;
}
cell响应3D Touch,所以在UITableViewController的-tableView:cellForRowAtIndexPath:中将cell注册为响应的源视图
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.textLabel.text = _data[indexPath.row];
#ifdef __IPHONE_9_0
if ([self Check3DTouch])
{
[self registerForPreviewingWithDelegate:self sourceView:cell];
}
#endif
return cell;
}
响应3D Touch的控制器需要遵守协议<UIViewControllerPreviewingDelegate>,实现如下两个协议方法
#pragma mark -UIViewControllerPreviewing Delegate
//Peek代理方法
-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
//获得当前cell的indexPath
NSIndexPath * index = [self.tableView indexPathForCell:(UITableViewCell *)previewingContext.sourceView];
UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
TextViewController * textVC = [storyBoard instantiateViewControllerWithIdentifier:@"text"];
[textVC setValue:_data[index.row] forKey:@"title"];
return textVC;
}
//pop代理方法
-(void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
{
[self showViewController:viewControllerToCommit sender:self];
}
看一下效果图
peek效果图 pop效果图
有的时候会想在peek的时候出现底部菜单,那么被弹出来的ViewController中就要遵守协议<UIPreviewActionItem>,实现如下方法
那么这个Demo楼主在TextViewController中实现如下方法
#pragma mark - UIPreviewActionItem
-(NSArray<id<UIPreviewActionItem>> *)previewActionItems
{
UIPreviewAction * act1 = [UIPreviewAction actionWithTitle:@"3D Touch" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
//添加点击处理操作
}];
UIPreviewAction * act2 = [UIPreviewAction actionWithTitle:@"点个赞啊" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
}];
UIPreviewAction * act3 = [UIPreviewAction actionWithTitle:@"小心啊" style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
}];
return [NSArray arrayWithObjects:act1,act2,act3, nil];
}
效果图: