美文网首页
右滑手势的封装

右滑手势的封装

作者: 涛涛灬灬 | 来源:发表于2017-03-29 21:26 被阅读0次

    使用runtime实现侧滑pop效果-ios黑魔法

    第一步:配置实现黑魔法

    在项目中如果每个相同的类中要实现相同的代码,如果需求不改,那万事大吉,如果需要改动一个方法,每个一个类中都需要改动一下,那就呵呵了.

    • 1.创建一个UIVIewController的类别
    • 2.使用runtime,导入头文件#import <objc/runtime.h>
    • 3.创建一个load方法;获取都走viewdidload方法的对象
    + (void)load
    {
        SEL systemDidLoadSel = @selector(viewDidLoad);
        SEL customDidLoadSel = @selector(swizzleviewDidLoad);
        
        [UIViewController swizzleSystemSel:systemDidLoadSel implementationCustomSel:customDidLoadSel];
    }
    
    • 4.runtime的一个代码的封装处理
    + (void)swizzleSystemSel:(SEL)systemSel implementationCustomSel:(SEL)customSel
    {
        Class cls = [self class];
        Method systemMethod =class_getInstanceMethod(cls, systemSel);
        Method customMethod =class_getInstanceMethod(cls, customSel);
        
        // BOOL class_addMethod(Class cls, SEL name, IMP imp,const char *types) cls被添加方法的类,name: 被增加Method的name, imp 被添加的Method的实现函数,types被添加Method的实现函数的返回类型和参数的字符串
        BOOL didAddMethod = class_addMethod(cls, systemSel, method_getImplementation(customMethod), method_getTypeEncoding(customMethod));
        if (didAddMethod)
        {
            class_replaceMethod(cls, customSel, method_getImplementation(systemMethod), method_getTypeEncoding(customMethod));
        }
        else
        {
            method_exchangeImplementations(systemMethod, customMethod);
        }
    }
    
    • 5 封装结束,开始进行方法的处理
    -(void)swizzleviewDidLoad{
    //此处可以写你需要的方法
        [self creactRightGesture];
    
    }
    

    第二步:实现侧滑方法

    在项目的工程中,每个界面都要实现左侧划返回上个界面的效果,如果在每个ViewController中都使用UIScreenEdgePanGestureRecognizer的话,代码量大,管理麻烦(已经踩过坑了);

    • 1.创建优化手势
    
    #pragma mark 右滑返回上一级_________
    ///右滑返回上一级
    -(void)creactRightGesture{
        id target = self.navigationController.interactivePopGestureRecognizer.delegate;
        UIScreenEdgePanGestureRecognizer *leftEdgeGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
        leftEdgeGesture.edges = UIRectEdgeLeft;
        leftEdgeGesture.delegate = self;
        [self.view addGestureRecognizer:leftEdgeGesture];
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        
    }
    
    
    • 2.实现系统方法,筛选出自己的手势方法,避免冲突:
    
    - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
    {
        return YES;
    }
    
    -(void)handleNavigationTransition:(UIScreenEdgePanGestureRecognizer *)pan{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    

    相关文章

      网友评论

          本文标题:右滑手势的封装

          本文链接:https://www.haomeiwen.com/subject/livyottx.html