3D Touch 的第二个功能:预览和弹出视图
1、创建一个viewcontroller作为window的rootviewcontroller(xcode7 这个需要设置,否则会崩溃)
2、创建一个预览视图控制器peekViewController,展示peek的内容,同时实现
3、viewcontroller控制器签署协议
UIViewControllerPreviewingDelegate(该协议是iOS9新特性)
4、在viewdidload里面检测是否支持3D Touch,设置代理
//必须进行是否支持3D Touch,3D Touch可以被关闭,还有一些ios设备不支持
if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
[self registerForPreviewingWithDelegate:self sourceView:self.view];
}
5、在viewcontroller里实现协议方法
//peek
- (nullable UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location NS_AVAILABLE_IOS(9_0)
{
PeekViewController *vc = [[PeekViewController alloc]init];
//设置预览视图的大小
vc.preferredContentSize = CGSizeMake(0, 330);
//设置点击位置出现的白色块的大小
previewingContext.sourceRect = CGRectMake(20, location.y - 10, [UIScreen mainScreen].bounds.size.width - 40, 50);
return vc;
}
//pop 方法
- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit NS_AVAILABLE_IOS(9_0)
{
//可以进行视图跳转等操作
[self.Navgationviewcontroller pushViewController:viewControllerToCommit animated:NO completion:nil];
}
6、在peekviewcontroller里面实现
-(NSArray<id<UIPreviewActionItem>> *)previewActionItems方法
-(NSArray<id<UIPreviewActionItem>> *)previewActionItems
{
NSMutableArray *actionItemArray = [NSMutableArray array];
UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"自定义1" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
//实现自己的逻辑处理
}];
UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"自定义2" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
}];
[actionItemArray addObject:action1];
[actionItemArray addObject:action2];
return actionItemArray;
}