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