右滑手势的封装

使用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];
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,734评论 25 709
  • 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的...
    西木阅读 30,720评论 33 466
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,847评论 0 9
  • 送你一朵玫瑰 千言万语皆化为 一句说不完的情话 一首写不完的诗行 一条永远走不完的路 十年 二十年 …… 直到我...
    萧路遥阅读 1,586评论 6 11
  • 我买的最贵的东西是什么?什么是贵,千金难买心头好,假如你认为你买的东西值,用处多,那就可以定位为值。价值比价...
    我是落枫阅读 2,860评论 2 0