2016-03-04 11:21:39 wang_gwei 阅读数 373


首先 有几个要知道的手势

第一, 在点击app icon 的手长按 并且用力一点(用点力不然没效果,不会弄坏手机,坏了也不是我的,哈哈!) 就会出现 几个Item。

第二,(1)在app 里面 长按 也要用力往下压 跟着就会可以弹出 自定义的 ViewController。这个时候如果你放手了那么就会消失。

           (2)如果  长按 往下压 弹出了自定义的ViewController 之后跟着网上移动,就可以出现 选择Action。

第三如果 长按 往下压 弹出了自定义的ViewController,然后更加 用力一点 比 弹出的ViewController的力度 更加大一点 那么  自定义的这个ViewController 就会 相当于push 进来了。

首先来一个获取版本号,因为3D Touch 只有在iOS9 才会有,在后面演示的代码就不上这个判断。

#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]

1、首先在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  去创建 item ,这几个item 就是在点击icon 的时候出现的.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    BOOL result = YES;
    
    //系统版本适配
    if (IOS_VERSION < 9.0) return result;
    
    NSArray *items = [UIApplication sharedApplication].shortcutItems;
    if (items.count == 0) {
        //也可以在info.plist 中创建
        [self createShortIcon];
    }
    //判断是否是从shortitem 启动的程序
    if (launchOptions[@"UIApplicationLaunchOptionsShortcutItemKey"]) {
        _currentShortItem = launchOptions[@"UIApplicationLaunchOptionsShortcutItemKey"];
        //这里返回值很重要、返回no,不会再调用performActionForShortcutItem这个回调方法
//        result = NO;
    }
    
        
    return result;
}

- (void)createShortIcon {

    UIApplicationShortcutIcon *shortIcon1 = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeHome];
    UIApplicationShortcutItem *shortItem1 = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.First",BundleId] localizedTitle:@"FistItem" localizedSubtitle:@"subtitle" icon:shortIcon1 userInfo:nil];
    
    UIApplicationShortcutIcon *shortIcon2 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"home@2x.png"];
    UIApplicationShortcutItem *shortItem2 = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.Second",BundleId] localizedTitle:@"SecondItem" localizedSubtitle:nil icon:shortIcon2 userInfo:nil];
    
    [[UIApplication sharedApplication] setShortcutItems:@[shortItem1,shortItem2]];
}

/**
    处理shortcotItem
 */
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {

    [self handleItem:shortcutItem];
}

- (void)handleItem:(UIApplicationShortcutItem *)shortItem {

    //处理shortitem事件
    if ([shortItem.type isEqualToString:[NSString stringWithFormat:@"%@.First",BundleId]]) {
        NSLog(@"First Item-----%@>>>>>>%@",[NSBundle mainBundle],[NSBundle mainBundle].bundleIdentifier);
    }else if ([shortItem.type isEqualToString:[NSString stringWithFormat:@"%@.Second",BundleId]]) {
        NSLog(@"Second Item-----%@>>>>>>%@",[NSBundle mainBundle],[NSBundle mainBundle].bundleIdentifier);
    }

    [self showAlert];
}

- (void)showAlert {

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"aaa" message:[NSString stringWithFormat:@"%d",22] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
    [alertView show];
}


//在每次激活程序时先置空一些设置

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    if (!_currentShortItem) return;
    
    [self handleItem:_currentShortItem];
    _currentShortItem = nil;
    
}

2、接着这里要说的是 在 长按touch ViewController  中tableView 对应Cell 添加Touch 事件

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdenfitier = @"CellId";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdenfitier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdenfitier];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    cell.textLabel.text = _cellArr[indexPath.row];
    
    if (IOS_VERSION >= 9.0 && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
        
        [self registerForPreviewingWithDelegate:self sourceView:cell];
    }
    
    return cell;
}

在viewController 中实现 Touch 协议方法


#pragma mark - UIViewControllerPreviewingDelegate

- (nullable UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
//重按时显示的预览界面
    return self.vc;
}


- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    //继续用力按执行执行这个方法, 这里事件预览界面展示出来
    [self showViewController:self.vc sender:self];
}

//重按显示预览界面时,向上滑动出现的菜单选择、一定要在
//-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
//回调返回的UIViewController中实现这个方法,不然无法显示菜单选项
- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {

    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"you" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        UIViewController *vc = [UIViewController new];
        [vc.view setBackgroundColor:[UIColor greenColor]];
        [[self topViewController] presentViewController:vc animated:YES completion:nil];
        
    }];
    
    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"and" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        UIViewController *vc = [UIViewController new];
        [vc.view setBackgroundColor:[UIColor greenColor]];
        [[self topViewController].navigationController pushViewController:vc animated:YES];
    }];
    
    UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"I" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        
    }];
    
    return @[action1, action2, action3];

}

- (UIViewController *)topViewController {

    return [self topviewControllerViewRootViewController:[UIApplication sharedApplication].delegate.window.rootViewController];
}

- (UIViewController *)topviewControllerViewRootViewController:(UIViewController *)rootViewController {

    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabbarController = (UITabBarController *)rootViewController;
        
        return [self topviewControllerViewRootViewController:tabbarController.selectedViewController];
    }else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
    
        UINavigationController *navigationController = (UINavigationController *)rootViewController;
        return [self topviewControllerViewRootViewController:navigationController.visibleViewController];
        /**
         * topViewController代表当前navigation栈中最上层的VC,而visibleViewController代表当前可见的VC,它可能是topViewController,也可能是当前topViewController present出来的VC。因此UINavigationController的这两个属性通常情况下是一样,但也有可能不同。
         */
    }else if (rootViewController.presentedViewController){
    
        UIViewController *presentViewController = rootViewController.presentedViewController;
        return [self topviewControllerViewRootViewController:presentViewController];
        /**
         *  presentedViewController:The view controller that is presented by this view controlller(read-only),被本视图控制器present出来的的视图控制器(只读)
         
         presentingViewController:The view controller that presented this view controller. (read-only),present出来本视图控制器的视图控制器(只读)
         
         parentViewController:The parent view controller of the recipient(容器). (read-only)
         
         */
    }else {
    
        return rootViewController;
    }
}

3、在自定义的vc弹出时 然后我们往上移动那么就会出现Action

//重按显示预览界面时,向上滑动出现的菜单选择、一定要在
//-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
//回调返回的UIViewController中实现这个方法,不然无法显示菜单选项
- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {

    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"you" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        UIViewController *vc = [UIViewController new];
        [vc.view setBackgroundColor:[UIColor greenColor]];
        [[self topViewController] presentViewController:vc animated:YES completion:nil];
        
    }];
    
    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"and" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        UIViewController *vc = [UIViewController new];
        [vc.view setBackgroundColor:[UIColor greenColor]];
        [[self topViewController].navigationController pushViewController:vc animated:YES];
    }];
    
    UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"I" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        
    }];
    
    return @[action1, action2, action3];

}

- (UIViewController *)topViewController {

    return [self topviewControllerViewRootViewController:[UIApplication sharedApplication].delegate.window.rootViewController];
}

- (UIViewController *)topviewControllerViewRootViewController:(UIViewController *)rootViewController {

    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabbarController = (UITabBarController *)rootViewController;
        
        return [self topviewControllerViewRootViewController:tabbarController.selectedViewController];
    }else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
    
        UINavigationController *navigationController = (UINavigationController *)rootViewController;
        return [self topviewControllerViewRootViewController:navigationController.visibleViewController];
        /**
         * topViewController代表当前navigation栈中最上层的VC,而visibleViewController代表当前可见的VC,它可能是topViewController,也可能是当前topViewController present出来的VC。因此UINavigationController的这两个属性通常情况下是一样,但也有可能不同。
         */
    }else if (rootViewController.presentedViewController){
    
        UIViewController *presentViewController = rootViewController.presentedViewController;
        return [self topviewControllerViewRootViewController:presentViewController];
        /**
         *  presentedViewController:The view controller that is presented by this view controlller(read-only),被本视图控制器present出来的的视图控制器(只读)
         
         presentingViewController:The view controller that presented this view controller. (read-only),present出来本视图控制器的视图控制器(只读)
         
         parentViewController:The parent view controller of the recipient(容器). (read-only)
         
         */
    }else {
    
        return rootViewController;
    }
}












2015-10-20 20:23:17 longitachi 阅读数 1270

3D Touch 是随着iPhone6s 和iPhone6s Plus 的推出,在两款机器上携带的一个非常有特色的功能,可以根据用户点击时的用力成都实现与用户的交互。

开发3D Touch 的话,Xcode必须是7.0之上版本,手机则需要iPhone6s之后并且系统在iOS9.0之上的手机。

写的一个小Demo:http://download.csdn.net/detail/longitachi/9197849,欢迎下载,效果图两张





一,3D Touch可以再我们点击屏幕icon图标时候,来进行一些快捷的操作方式。

实现这个效果有两种方式,一种是静态的实现方式,直接在项目总info.plist文件中添加如下字段(如下图)

第二种是动态方式创建

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //创建方式有多种,下面举得例子为创建可变的标签
    UIApplicationShortcutIcon *icon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"imageName"];
    UIMutableApplicationShortcutItem *item = [[UIMutableApplicationShortcutItem alloc] initWithType:@"type" localizedTitle:@"标题" localizedSubtitle:@"子标题" icon:icon userInfo:@{@"key": @"value"}];
    [UIApplication sharedApplication].shortcutItems = @[item];
    
    // Override point for customization after application launch.
    NSLog(@"%s, %@", __FUNCTION__, launchOptions);
    return YES;
}
需要注意的是,如果需要点击icon图标出现的标签携带图片,那么图片的尺寸需要是35*35像素的(官方介绍:Icons should be square, single color, and 35x35 points, as shown in these template files and as described in iOS Human Interface Guidelines.
完成之上操作后,你便可以运行你的Demo去尝试一下3DTouch了。

相应的,我们可以在AppDelegate中实现如下方法来实现不同的效果

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
    NSLog(@"shortcutItem%@", shortcutItem);
}


二,在应用内部实现3D Touch功能

当我们使用短信和微信、新浪微博等应用时,我们发现其应用内部也有 3D Touch 功能,效果如如下


而且这时候如果我们轻轻地上推,还会出现一些快捷操作,如下图


实现该功能并不难。当前类需要遵守协议:UIViewControllerPreviewingDelegate

接下来我们为每个表格的cell添加3dtouch

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    //注册该方法
    [self registerForPreviewingWithDelegate:self sourceView:cell];
    
    return cell;
}


接下来便是实现协议中的方法

- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //获取到indexPath,那么接下来做对应的事情就看你自己的需求了
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)previewingContext.sourceView];
    
    UIViewController *vc = [[UIViewController alloc] init];
    vc.preferredContentSize = CGSizeMake(0.0f, [[UIScreen mainScreen] bounds].size.height - 100);
    
    return vc;
}

- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
{
    [self showViewController:viewControllerToCommit sender:self];
}


上面步骤实现后,我们会发现点击屏幕任意地方就会看到SecViewController的缩略图了,但是向上滑并没有上面短信界面的快捷回复,实现这个功能我们需要在SecViewcontroller中实现- (NSArray<id<UIPreviewActionItem>> *)previewActionItems; 这个方法,如下

- (NSArray<id<UIPreviewActionItem>> *)previewActionItems
{
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"title1" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"点击了title1");
    }];
    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"title2" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        NSLog(@"点击了title2");
    }];
    
    [arr addObject:action1];
    [arr addObject:action2];
    
    return arr;
}

到这里基础的3D Touch功能便实现了。



2016-10-19 18:20:37 qq_30936699 阅读数 1127

        个人对IOS端3D Touch功能很感兴趣,想来自己实现,上网一搜,这类文章并不是很多,于是想自己实现一个。在自己绞尽脑汁的时候在github上搜索到一个开源项目可以实现简单3D Touch功能,在此坐一下笔记,以供后续参考。

话不多说,贴出核心代码:

//设置PeekView选项
PeekViewOptions options = new PeekViewOptions();
options.setBackgroundDim(1f);           // range: 0  - 1  (default is .6)   背景模糊度
options.setHapticFeedback(false);       // default is true

// it may be a good idea to set set these through resources so that you can use different options based on screen size and orientation
options.setWidthPercent(.4f);           // range: .1 - .9 (default is .6)
options.setHeightPercent(.4f);          // range: .1 - .9 (default is .5)

// you can also set the size of the PeekView using absolute values, instead of percentages.
// Setting these will override the corresponding percentage value.
// You should use this instead of setting the size of the view from the layout resources, as those get overridden.
options.setAbsoluteWidth(200);          // 200 DP
options.setAbsoluteHeight(200);         // 200 DP

// default is false. If you change this to true, it will ignore the width and height percentages you set.
options.setFullScreenPeek(true);
// default is true. Unless you are going to animate things yourself, i recommend leaving this as true.
//options.setFadeAnimation(false);
options.setUseFadeAnimation(true);

// PeekView has the ability to blur the background behind it, instead of just using a simple dark dim.
// If you set a blurred view, then it will invalidate whatever you set as your background dim.
// If you do this, please look at the installation steps for the blur effect, or the app will crash.
options.setBlurBackground(true);                            // default is true
// options.setBlurOverlayColor(Color.parse("#99000000"));      // #99000000 default
options.setBlurOverlayColor(Color.parseColor("#99000000"));    //背景颜色

//Peek.into(...).with(options).applyTo(...);


Peek.into(R.layout.image_peek, new SimpleOnPeek() {
    @Override
    public void onInflated(View rootView) {
        WebView mWebView = (WebView) rootView.findViewById(R.id.mWebView);
        final ProgressBar mProgressBar = (ProgressBar) rootView.findViewById(R.id.mProgressBar);
        mWebView.loadUrl("http://www.baidu.com");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress==100) {
                    mProgressBar.setVisibility(View.GONE);

                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                }
                mProgressBar.setProgress(newProgress);

                super.onProgressChanged(view, newProgress);
            }


        });


    }
}).with(options).applyTo(this, baseView);

2016-03-23 19:05:09 Sir_Coding 阅读数 351
3D Touch,就是屏幕可感应不同的感压力度触控,有Peek Pop 两种新手势。
6s出来的时候,我对这增加的新功能激动不已 ~ ~
想着新技术,新玩意,App会越来越好的 ~ ~

3D Touch目前实现的功能,该实现的也实现了。现在把之前自己写项目的相关代码检出来供大家参考。

  • 写在前面
    是从iOS 9之后的系统支持的,UIViewController的.h文件中是这样地:
// 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);

so,注册前判断下系统还是相当有必要的,判断的宏定义我也给搞出来,哈哈

#define SC_IOS9 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9)

if (SC_IOS9)
{
    //注册
    if (SC_IOS9)
    {
        //注册
        [self registerForPreviewingWithDelegate:self sourceView:mealsHistoryTableView];;
}
  • 第一弹: 快捷图标进入App

    第一步:给快捷入口增加两个item

if (SC_IOS9)
    {
        //注册
        [self threeDTouchForQuickOpenTheAppWithApplication:application];
    }
#pragma mark - 3D图标快捷功能进入
/**
 *  3Dtouch快捷进入图标
 *
 *  @param application 当前程序
 */
-(void)threeDTouchForQuickOpenTheAppWithApplication:(UIApplication *)application{
    //第一个设置图标img
    UIApplicationShortcutIcon *icon1 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"chatShowCal"];
    //创建第一个快捷入口
    UIApplicationShortcutItem *item1 = [[UIApplicationShortcutItem alloc]initWithType:noti_3dtouch_chatWithShowCal localizedTitle:@"咨询瘦咖" localizedSubtitle:nil icon:icon1 userInfo:nil];

    UIApplicationShortcutIcon *icon2 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"camera"];
    UIApplicationShortcutItem *item2 = [[UIApplicationShortcutItem alloc]initWithType:noti_3dtouch_takePhotoOfFood localizedTitle:@"拍照上传" localizedSubtitle:nil icon:icon2 userInfo:nil];
    //添加进去
    application.shortcutItems = @[item1,item2];
    }
第二步:响应该快捷入口,苹果提供的接收方法是:
// Called when the user activates your application by selecting a shortcut on the home screen,
// except when -application:willFinishLaunchingWithOptions: or -application:didFinishLaunchingWithOptions returns NO.
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void(^)(BOOL succeeded))completionHandler NS_AVAILABLE_IOS(9_0) __TVOS_PROHIBITED;

实现该方法 :

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem
  completionHandler:(void(^)(BOOL succeeded))completionHandler
{
    //判断唯一标示 确定相对应的按钮
    if([shortcutItem.type isEqualToString:noti_3dtouch_chatWithShowCal]){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:noti_3dtouch_chatWithShowCal object:nil];
        });

    }

    //判断唯一标示 确定相对应的按钮
    if([shortcutItem.type isEqualToString:noti_3dtouch_takePhotoOfFood]){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:noti_3dtouch_takePhotoOfFood object:nil];
        });

    }
}

OK,你可以搞下来试试了。效果如下,估计想也想到是什么效果了。。
这里写图片描述

  • 第二弹:TableView实现Cell上的展示预览(peek)

,,随后见,饿的不行了,下班回家吃饭。

2016-03-16 10:25:33 u010277446 阅读数 940

3D Touch正在改变用户的操作习惯,体验了下,确实挺酷。  做为个开发者,一定想知道如何才能集成这样操作功能。

话不多说,直接上代码(因为3D Touch的开发资料网止已经太多了,不说了)


尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬尴尬

一、3D Touch重按主屏icon出现快捷标签有两种添加方式:
1.静态添加,在工程中的info.plist文件中添加,这种方式添加的标签安装后就能显示



2.动态添加,通过代码动态添加快速入口。这种方式添加的标签,必须先运行一次App才会出现。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    [selfconfigShortCutItems];

    //很多资料上查到要判断,但发现我加上之后通过标签启动时不会加载预览界面

//    if (launchOptions[@"UIApplicationLaunchOptionsShortcutItemKey"] == nil)

//    {

        return YES;

//    }

//    else

//    {

//        return NO;

//    }

}


- (void)configShortCutItems

{

    UIApplicationShortcutIcon *icon1 = [UIApplicationShortcutIconiconWithType:UIApplicationShortcutIconTypePlay];

    UIMutableApplicationShortcutItem *item1 = [[UIMutableApplicationShortcutItemalloc]initWithType:@"888"localizedTitle:@"play"localizedSubtitle:@"动态添加的标签"icon:icon1userInfo:nil];

    

    UIApplicationShortcutIcon *icon2 = [UIApplicationShortcutIconiconWithTemplateImageName:@"shareIcon"];

    UIMutableApplicationShortcutItem *item2 = [[UIMutableApplicationShortcutItemalloc]initWithType:@"999"localizedTitle:@"自定义图标"localizedSubtitle:@"呵呵"icon:icon2userInfo:nil];

    

    [UIApplicationsharedApplication].shortcutItems =@[item1,item2];

}


需要说明一点,主屏呼出的快捷标签,静态和动态添加的共只能有四个。

3D Touch在appdelegate.m代理方法:

#pragma mark - 3D Touch

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void(^)(BOOL succeeded))completionHandler{

    //判断设置的唯一标识,区分点击的是哪一个标签来响应不同事件

    if([shortcutItem.typeisEqualToString:@"666"]){

        DDDTouchVC *vc = [[DDDTouchVC allocinit];

        McUINavigationController *nav_VC = [[McUINavigationController allocinitWithRootViewController:vc];

        [nav_VC setBackgroundImage:[UIImage imageNamed:@"nav_bg"]];

        [self.window.rootViewController presentViewController:nav_VC animated:YES completion:^{

        }];

        return;

    }

    if([shortcutItem.typeisEqualToString:@"777"]){


        DDDTouchVC *vc = [[DDDTouchVC allocinit];

        McUINavigationController *nav_VC = [[McUINavigationController allocinitWithRootViewController:vc];

        [nav_VC setBackgroundImage:[UIImage imageNamed:@"nav_bg"]];

        [self.window.rootViewController presentViewController:nav_VC animated:YES completion:^{

        }];

        return;

    }

    if ([shortcutItem.typeisEqualToString:@"888"]) {

        DDDTouchVC *vc = [[DDDTouchVC allocinit];

        McUINavigationController *nav_VC = [[McUINavigationController allocinitWithRootViewController:vc];

        [nav_VC setBackgroundImage:[UIImage imageNamed:@"nav_bg"]];

        [self.window.rootViewController presentViewController:nav_VC animated:YES completion:^{

        }];

        return;

    }

    if ([shortcutItem.typeisEqualToString:@"999"]) {

        NSArray *arr = @[@"3D Touch"];

        UIActivityViewController *vc = [[UIActivityViewController allocinitWithActivityItems:arr applicationActivities:nil];

        [self.window.rootViewController presentViewController:vc animated:YES completion:^{

        }];

        return;

    }

}


至此,通过重按主屏触发3D Touch 呼出快捷标签和点击分别响应操作已集成完毕!


二、3D Touch 的peek和pop功能在tableView上的简单实现

话不多说,直接上代码

1.peek预览

DDDTouchVC.h

#import <UIKit/UIKit.h>


@interface DDDTouchVC :UIViewController


@end



这是主控制器,有tableView,也是3D Touch的代理控制器需求实现 UIViewControllerPreviewingDelegate 协议

DDDTouchVC.m

#import "DDDTouchVC.h"

#import "DDDTouchPeekVC.h"


@interface DDDTouchVC ()<UIViewControllerPreviewingDelegate,UITableViewDataSource,UITableViewDelegate>


@property (nonatomic,retain)NSMutableArray *arrData;

@property (nonatomic,retain)UITableView *tableView;


@implementation DDDTouchVC


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];

    self.title =@"3D Touch";

    

    UIButton *back = [UIButtonbuttonWithType:UIButtonTypeCustom];

    back.frame = CGRectMake(0,0,40,25);

    [back setTitle:@"exit" forState:UIControlStateNormal];

    [back setTitleColor:[UIColor lightGrayColorforState:UIControlStateNormal];

    [back setTitleColor:[UIColor whiteColorforState:UIControlStateHighlighted];

    [back addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *leftItem = [[UIBarButtonItem allocinitWithCustomView:back];

    [self.navigationItem setLeftBarButtonItem:leftItemanimated:YES];

    

    [selfinitTableView];

    

    //检测是否支持3D Touch...

    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {

        //支持

//        [self registerForPreviewingWithDelegate:self sourceView:self.view];

    }

    else

    {

        //不支持

       UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"手机不支持3D Touch..." message:nil delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil,nil];

        [alert show];

    }

}


- (void)initTableView

{

        //百度随便找了些图片链接

    NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"http://a.hiphotos.baidu.com/image/h%3D360/sign=1698b41ebb389b5027ffe654b535e5f1/a686c9177f3e6709e974ebff39c79f3df8dc55bd.jpg" forKey:@"1"];

    NSDictionary *dic2 = [NSDictionary dictionaryWithObject:@"http://b.hiphotos.baidu.com/image/h%3D360/sign=ff34dff8bd389b5027ffe654b537e5f1/a686c9177f3e670900d880193fc79f3df9dc5578.jpg" forKey:@"2"];

    NSDictionary *dic3 = [NSDictionary dictionaryWithObject:@"http://a.hiphotos.baidu.com/image/h%3D360/sign=f527ab2f4b540923b5696578a259d1dc/dcc451da81cb39dbce6b325ad2160924ab183016.jpg" forKey:@"3"];

    NSDictionary *dic4 = [NSDictionary dictionaryWithObject:@"http://d.hiphotos.baidu.com/image/h%3D360/sign=81d5d22779f40ad10ae4c1e5672d1151/d439b6003af33a8762fee505c45c10385343b51a.jpg" forKey:@"4"];

    NSDictionary *dic5 = [NSDictionary dictionaryWithObject:@"http://d.hiphotos.baidu.com/image/h%3D200/sign=8d3a52a04ded2e73e3e9812cb701a16d/f7246b600c33874450b89258560fd9f9d72aa091.jpg" forKey:@"5"];

    NSDictionary *dic6 = [NSDictionary dictionaryWithObject:@"http://h.hiphotos.baidu.com/image/h%3D360/sign=e53dee25d5ca7bcb627bc1298e086b3f/a2cc7cd98d1001e9ae32c3e9ba0e7bec55e797ce.jpg" forKey:@"6"];

    NSDictionary *dic7 = [NSDictionary dictionaryWithObject:@"http://g.hiphotos.baidu.com/image/h%3D360/sign=8cb0e6191a178a82d13c79a6c602737f/6c224f4a20a446230761b9b79c22720e0df3d7bf.jpg" forKey:@"7"];

    NSDictionary *dic8 = [NSDictionary dictionaryWithObject:@"http://a.hiphotos.baidu.com/image/h%3D360/sign=80285822f9f2b211fb2e8348fa806511/bd315c6034a85edf1da1c0724b540923dd5475b5.jpg" forKey:@"8"];

    NSDictionary *dic9 = [NSDictionarydictionaryWithObject:@"http://e.hiphotos.baidu.com/image/h%3D360/sign=708629f379cb0a469a228d3f5b62f63e/7dd98d1001e939015d4a463779ec54e736d1966b.jpg"forKey:@"9"];

    NSDictionary *dic10 = [NSDictionary dictionaryWithObject:@"http://h.hiphotos.baidu.com/image/h%3D360/sign=95102c30bc096b639e1958563c338733/3801213fb80e7beccbb1e8fe2d2eb9389b506b42.jpg" forKey:@"10"];

    NSDictionary *dic11 = [NSDictionary dictionaryWithObject:@"http://a.hiphotos.baidu.com/image/h%3D360/sign=cbd227bf8e5494ee9822091f1df5e0e1/c2cec3fdfc039245ee84470f8594a4c27d1e25f8.jpg" forKey:@"11"];

    NSDictionary *dic12 = [NSDictionary dictionaryWithObject:@"http://e.hiphotos.baidu.com/image/h%3D360/sign=87824d652adda3cc14e4be2631e83905/b03533fa828ba61e64671cd54534970a314e59bb.jpg" forKey:@"12"];

    _arrData = [[NSMutableArray allocinitWithObjects:dic1,dic2,dic3,dic4,dic5,dic6,dic7,dic8,dic9,dic10,dic11,dic12,nil];

    _tableView = [[UITableView allocinitWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height-64)style:UITableViewStylePlain];

    _tableView.dataSource =self;

    _tableView.delegate =self;

    [self.viewaddSubview:_tableView];

}

 

#pragma mark - 3D Touch Peek和pop代理

- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location

{

    //对每个cell进行注册代理方法:[self registerForPreviewingWithDelegate:self sourceView:cell];

    //通过[previewingContext sourceView]拿到tableView对应的cell

    NSIndexPath *indexPath = [_tableView indexPathForCell:(UITableViewCell* )[previewingContext sourceView]];

    NSString *imageURL = [[[_arrData objectAtIndex:indexPath.rowallValuesobjectAtIndex:0];

    DDDTouchPeekVC *peekVC = [[DDDTouchPeekVC allocinitWithImageURL:imageURL];

    peekVC.view.backgroundColor = [UIColor greenColor];

    NSLog(@"%@",location);

    return peekVC;

}


- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit

{

    viewControllerToCommit.hidesBottomBarWhenPushed =YES;

    [self showViewController:viewControllerToCommit sender:self];

//    [self.navigationController pushViewController:viewControllerToCommit animated:NO];

}


#pragma mark - UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 50;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    if (_arrData &&_arrData.count >0) {

        return _arrData.count;

    }

    return 1;

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *cellID =@"LMChao";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    

    if (cell == nil) {

        cell = [[UITableViewCell allocinitWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellID];

        //注册Peek高亮来源***

        [self registerForPreviewingWithDelegate:self sourceView:cell];

    }

    

    if (_arrData && indexPath.row < [_arrDatacount])

    {

        cell.textLabel.text = [[[_arrData objectAtIndex:indexPath.rowallKeysobjectAtIndex:0];

    }

    return cell;

}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    //do somthing...

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}



2.pop界面控制器

DDDTouchPeekVC.h

#import <UIKit/UIKit.h>


@interface DDDTouchPeekVC : UIViewController


@property (nonatomic,retain)NSString *imageURL;


- (id)initWithImageURL:(NSString *)imageURL;

@end



DDDTouchPeekVC.m

#import "DDDTouchPeekVC.h"


@interface DDDTouchPeekVC ()

{

    UIImageView *_photoView;

}


@property (nonatomic,copy)NSString *etag;

@end


@implementation DDDTouchPeekVC


- (id)initWithImageURL:(NSString *)imageURL

{

    if (self = [superinit]) {

        //do somthing..

        _imageURL = imageURL;

    }

    return self;

}


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    

    self.view.backgroundColor = [UIColor whiteColor];

    

    UIButton *back = [UIButtonbuttonWithType:UIButtonTypeCustom];

    back.frame = CGRectMake(0,0,40,25);

    [back setTitle:@"back" forState:UIControlStateNormal];

    [back setTitleColor:[UIColor lightGrayColorforState:UIControlStateNormal];

    [back setTitleColor:[UIColor whiteColorforState:UIControlStateHighlighted];

    [back addTarget:selfaction:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *leftItem = [[UIBarButtonItem allocinitWithCustomView:back];

    [self.navigationItem setLeftBarButtonItem:leftItem animated:YES];

    

    self.title =@"3D Touch PeekVC";

    

    _photoView = [[UIImageView allocinitWithFrame:CGRectMake(0,0,CGRectGetWidth(self.view.frame),CGRectGetHeight(self.view.frame)-64)];

    [self.viewaddSubview:_photoView];


    [self initData];

}



- (void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:YES];

}


- (void)viewDidDisappear:(BOOL)animated

{

    [super viewDidDisappear:YES];

}

- (void)backButtonClicked

{

    [self.navigationController popViewControllerAnimated:YES];

    

}

- (void)initData

{

    

    NSURL *url = [NSURLURLWithString:_imageURL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0timeoutInterval:10.0];

    

    if (self.etag.length >0) {

        [request setValue:self.etag forHTTPHeaderField:@"IF-None-Match"];

    }

    


    NSURLSessionDataTask *task = [[NSURLSession sharedSessiondataTaskWithRequest:request completionHandler:^(NSData *_Nullable data,NSURLResponse *_Nullable response,NSError *_Nullable error) {

        

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        

        

        NSLog(@"%@",httpResponse);

        

        if (error.code ==0) {

            dispatch_async(dispatch_get_main_queue(), ^{

                //显示图片

                _photoView.image = [UIImage imageWithData:data];

            });

        }

        

        self.etag = httpResponse.allHeaderFields[@"etag"];

        NSLog(@"%@",httpResponse.allHeaderFields);

        

    }];

    [task resume];

}



#pragma mark - 底部预览界面选项(peek界面时上滑弹起的快捷标签)

- (NSArray <id <UIPreviewActionItem>> *)previewActionItems

{

    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"呵呵"style:UIPreviewActionStyleDefault handler:^(UIPreviewAction *_Nonnull action, UIViewController *_Nonnull previewViewController) {

        NSLog(@"%s",__func__);

        UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"呵呵message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,nil];

        [alert show];

    }];

    

    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"嘿嘿"style:UIPreviewActionStyleDefault handler:^(UIPreviewAction *_Nonnull action, UIViewController *_Nonnull previewViewController) {

        NSLog(@"%s",__func__);

        UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"嘿嘿message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,nil];

        [alert show];

    }];

    

    UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"擦擦"style:UIPreviewActionStyleDefault handler:^(UIPreviewAction *_Nonnull action,UIViewController *_Nonnull previewViewController) {

        NSLog(@"%s",__func__);

        UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"擦擦..." message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,nil];

        [alert show];

    }];

    //想要显示多个就定义多个 UIPreviewAction

    NSArray *actions = @[action1,action2,action3];

    return actions;

}



- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



// 以下两个为默认设定,直接复制粘贴就行(网上看到网友有这样写的,好像可有可无)

// 根视图的返回

- (UIViewController*)topViewController

{

    return [self topViewControllerWithRootViewController:[UIApplicationsharedApplication].delegate.window.rootViewController];

}

// 根视图的类型

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController

{

    if ([rootViewController isKindOfClass:[UITabBarController class]]) {

        UITabBarController *tabBarController = (UITabBarController *)rootViewController;

        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];

    } else if ([rootViewControllerisKindOfClass:[UINavigationControllerclass]]) {

        UINavigationController* navigationController = (UINavigationController*)rootViewController;

        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];

    } else if (rootViewController.presentedViewController) {

        UIViewController* presentedViewController = rootViewController.presentedViewController;

        return [self topViewControllerWithRootViewController:presentedViewController];

    } else {

        return rootViewController;

    }

}



至此,3D Touch功能在tableView上列表的简单功能就完成了, 这边是peek 、pop展示的是加载一张百度连接的图片。匆忙而就,写得不详细,如有错误,谅解。。。

iOS之实现3D Touch

阅读数 627

ios9 3D Touch 实现

阅读数 349

没有更多推荐了,返回首页