iOS

3DTouch的使用

3DTouch是苹果新出的一种交互模式,我尝试在帖子列表页加入了这个功能,感觉还不错,记录下使用方法

Posted by yasin on May 24, 2016

1、给控件注册事件(以cell为例

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PostsFrameModel *model = _FrameArray[indexPath.row];
    PostsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostsCell"];
    cell.fModel=model;
    //注册3DTouch
    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        NSLog(@"3D Touch  可用!");
        //给cell注册3DTouch的peek(预览)和pop功能
        [self registerForPreviewingWithDelegate:self sourceView:cell];
    } else {
        NSLog(@"3D Touch 无效");
    }
    return cell;
}

2、实现代理方法

<UIViewControllerPreviewingDelegate>
//预览
- (nullable UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
    //获取按压的cell所在行,[previewingContext sourceView]就是按压的那个视图
    NSIndexPath *indexPath = [_tableview indexPathForCell:(UITableViewCell* )[previewingContext sourceView]];
    //设定预览的界面
    WebViewController *web = [[WebViewController alloc]init];
    PostsModel *model = _dataArray[indexPath.row];
    web.postsUrl=model.href;
    web.tid=model.tid;
    web.tTitle=model.subject;
    web.preferredContentSize = CGSizeMake(0.0f,500.0f);
    //调整不被虚化的范围,按压的那个cell不被虚化(轻轻按压时周边会被虚化,再少用力展示预览,再加力跳页至设定界面)
    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width,40);
    previewingContext.sourceRect = rect;
    //返回预览界面
    return web;
}

//pop按用点力进入
- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    viewControllerToCommit.hidesBottomBarWhenPushed=YES;
    [self showViewController:viewControllerToCommit sender:self];
}

3、在要进入的页面添加上滑快捷操作按钮

- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {
    // setup a list of preview actions
    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"Aciton1" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"Aciton1");
    }];
    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"Aciton2" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"Aciton2");
    }];
    UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"Aciton3" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"Aciton3");
    }];
    NSArray *actions = @[action1,action2,action3];
    // and return them (return the array of actions instead to see all items ungrouped)
    return actions;
}