iOS知识点iOS程序员的业余沙龙Swift&Objective-C

iOS 循环push同一种ViewController时,控制数

2017-07-29  本文已影响1051人  水暮竹妖

引子

新接手项目有这么个问题,商详页有推荐商品,推荐商品点进去又是商详页,用户可以无限push商详页,产品现在提出需求:只保留第一个产品和最后两个商品。

解决方案

代码

//   1.在要限制push次数的VC里添加头文件
#import "UIViewController+PushAndPop.h"

//   2.override下面的方法,返回的即是限制的个数
+ (NSUInteger)cyclePushLimitNumber {
    return 3;
}

 [self.navigationController setViewControllers:vcsArrM animated:YES];
//  UIViewController+PushAndPop.h
#import <UIKit/UIKit.h>

@interface UIViewController (PushAndPop)
+ (NSUInteger)cyclePushLimitNumber;
@end

//  UIViewController+PushAndPop.m
#import "UIViewController+PushAndPop.h"
#import <objc/runtime.h>

@implementation UIViewController (PushAndPop)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL originalSelector = @selector(viewDidLoad);
        SEL swizzledSelector = @selector(az_viewDidLoad);
        swizzleMethod([self class], originalSelector, swizzledSelector);
    });
}

//  注意下这个 static 
//  关于为啥要在C函数前加static,不知道&有兴趣的可以自己去两个不同的类创建相同的C方法试试:)
static void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector)
{
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)az_viewDidLoad {
    //   获取limitNum 
    NSUInteger limitNum = [[self class] cyclePushLimitNumber];
    if (limitNum <= 0) { // 0表示不限制数量 
        [self az_viewDidLoad];
        return;
    }
    
    NSArray *vcs = self.navigationController.viewControllers;
    NSMutableArray *productDetailVCIndexArrM = [NSMutableArray array];
    for (NSInteger i = vcs.count; i >= 0; i--) {
        //   从数组尾开始遍历有多少连续的VC
        if (![vcs[i - 1] isKindOfClass:[self class]]) {
            break;
        }
        [productDetailVCIndexArrM addObject:@(i - 1)];
    }
    
    if (productDetailVCIndexArrM.count > limitNum) {
        NSMutableArray *vcsArrM = [vcs mutableCopy];
        [vcsArrM removeObjectAtIndex:[productDetailVCIndexArrM[1] integerValue]];
        [self.navigationController setViewControllers:vcsArrM animated:YES];
    }
    [self az_viewDidLoad];
}

+ (NSUInteger)cyclePushLimitNumber {
    return 0;
}

@end

上一篇下一篇

猜你喜欢

热点阅读