右滑手勢的封裝

使用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閱讀 173,467評論 25 708
  • 這篇文章完全是基于南峰子老師博客的轉載 這篇文章完全是基于南峰子老師博客的轉載 這篇文章完全是基于南峰子老師博客的...
    西木閱讀 30,643評論 33 466
  • 轉至元數據結尾創建: 董瀟偉,最新修改于: 十二月 23, 2016 轉至元數據起始第一章:isa和Class一....
    40c0490e5268閱讀 1,776評論 0 9
  • 送你一朵玫瑰 千言萬語皆化為 一句說不完的情話 一首寫不完的詩行 一條永遠走不完的路 十年 二十年 …… 直到我...
    蕭路遙閱讀 240評論 6 11
  • 我買的最貴的東西是什么?什么是貴,千金難買心頭好,假如你認為你買的東西值,用處多,那就可以定位為值。價值比價...
    我是落楓閱讀 380評論 2 0