一個(gè)簡(jiǎn)單的控制器跳轉(zhuǎn)Router--GRRouter

git地址:https://github.com/Assuner-Lee/GRRouter.git

pod  'GRRouter'

前言

界面間的跳轉(zhuǎn),如果某個(gè)對(duì)象不能拿到導(dǎo)航控制器,需通過(guò)代理,block等方式 委托某個(gè)控制器去push或present,比較麻煩。因此,我們寫(xiě)了一個(gè)簡(jiǎn)單的Router去簡(jiǎn)化這些操作。

用法

push
 [GRRouter open:@"push->GRMenuViewController" params:@{@"shop": _cellDataArray[indexPath.row]}];
 [GRRouter open:@"push->GRMenuViewController?NO" params:@{@"shop":_shop]}];

 如上,假設(shè)_shop變量的所屬對(duì)象為一個(gè)cell,router初始化了一個(gè)類(lèi)為GRMenuViewController的控制器 vc,并將cell的_shop變量 賦予了vc的shop屬性上,最后router的hostViewController push了vc (?NO為沒(méi)有動(dòng)畫(huà))。
 [GRRouter open:@"push->GRTestViewControllerBeta" params:@{@"color": [UIColor blueColor], @"text": @"push1"}];
present
 [GRRouter open:@"present->GRLoginViewController" params:nil completed:^{[MBProgressHUD gr_showFailure:@"請(qǐng)先登錄"];}];
 [GRRouter open:@"present->GRTestViewControllerBeta" params:@{@"color": [UIColor blueColor], @"text": @"present1"}];
 [GRRouter open:@"present->GRTestViewControllerBeta?NO" params:@{@"color": [UIColor redColor], @"text": @"present2"}];

在此之前,我們需要設(shè)置GRRouter的hostViewController

簡(jiǎn)而言之,當(dāng)需要push,present其他控制器的時(shí)候,我們需要總能找到合適的發(fā)起者。

在某些情況下,您可以直接指定GRRouter的主控制器,比如主window的rootViewController為UINavigationController類(lèi)型:

 [GRRouter sharedRouter].hostViewController = [UIApplication sharedApplication].delegate.window.rootViewController;

如果控制器層次比較復(fù)雜,比如主window的rootViewController為UITabBarController類(lèi)型,這個(gè)UITabBarController對(duì)象的控制器數(shù)組里又放著若干個(gè)UINavigationController


圖片1

若想push下一個(gè)控制器,且不造成各個(gè)導(dǎo)航控制器棧的混亂,我們需要拿到UITabBarController當(dāng)前選中的控制器。
這時(shí),我們可以動(dòng)態(tài)設(shè)置Router的主控制器,如:

[GRRouter getDynamicHostViewController:^UIViewController *{
    return ((UITabBarController *)self.window.rootViewController).selectedViewController;
}];
發(fā)生了:
+ (void)getDynamicHostViewController:(GRHostBlock)block {
    [self sharedRouter].hostBlock = block;
}

簡(jiǎn)而言之,在push present發(fā)生前,router執(zhí)行block,將block返回的控制器賦給hostViewController。在此block里,你可以描述router在某些時(shí)機(jī)如何得到合適的跳轉(zhuǎn)發(fā)起者,如下。

- (UIViewController *)hostViewController {
    if (self.hostBlock) {
        _hostViewController = self.hostBlock();
    }
    return _hostViewController;
}

代碼實(shí)現(xiàn)

GRRouter.h

#import <UIKit/UIKit.h>

typedef void (^GRBlankBlock)(void);
typedef UIViewController * (^GRHostBlock)(void);

@interface GRRouter : NSObject

@property (nonatomic, strong) UIViewController *hostViewController;

+ (GRRouter *)sharedRouter;
+ (void)getDynamicHostViewController:(GRHostBlock)block;
+ (void)pushViewController:(UIViewController *)aVC animated:(BOOL)animated;
+ (void)presentViewController:(UIViewController *)aVC animated:(BOOL)animated completion:(GRBlankBlock)completion;
+ (void)open:(NSString *)url params:(NSDictionary *)params completed:(GRBlankBlock)block;
+ (void)open:(NSString *)url params:(NSDictionary *)params;

@end

GRRouter.m

#import "GRRouter.h"
#import <objc/runtime.h>

@interface GRRouter ()

@property (nonatomic, copy) GRHostBlock hostBlock;

@end

@implementation GRRouter

+ (GRRouter *)sharedRouter {
    static GRRouter *router = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        router = [[GRRouter alloc] init];
    });
    return router;
}

+ (UIViewController *)hostViewController {
    return [[self sharedRouter] hostViewController];
}

- (UIViewController *)hostViewController {
    if (self.hostBlock) {
        _hostViewController = self.hostBlock();
    }
    return _hostViewController;
}

//** 此方法可動(dòng)態(tài)指定主控制器,若為靜態(tài),請(qǐng)直接設(shè)置hostViewController
+ (void)getDynamicHostViewController:(GRHostBlock)block {
    [self sharedRouter].hostBlock = block;
}

+ (void)pushViewController:(UIViewController *)aVC animated:(BOOL)animated {
    UIViewController *hostVC = [self sharedRouter].hostViewController;
    if (hostVC) {
        if ([hostVC isKindOfClass:[UINavigationController class]]) {
            [(UINavigationController *)hostVC pushViewController:aVC animated:animated];
        } else {
            [NSException raise:@"GRRouterHostVCError" format:@"hostViewController of Router is not a UINavigationController"];
        }
    } else {
        [NSException raise:@"GRRouterHostVCError" format:@"hostViewController of Router is nil"];
    }
}

+ (void)presentViewController:(UIViewController *)aVC animated:(BOOL)animated completion:(GRBlankBlock)completion {
    UIViewController *hostVC = [self sharedRouter].hostViewController;
    if (hostVC) {
        if ([hostVC isKindOfClass:[UIViewController class]]) {
            [hostVC presentViewController:aVC animated:animated completion:completion];
        } else {
            [NSException raise:@"GRRouterHostVCError" format:@"hostViewController of Router is not a UIViewController but (%@)", NSStringFromClass([hostVC class])];
        }
    } else {
        [NSException raise:@"GRRouterHostVCError" format:@"hostViewController of Router is nil"];
    }
}



//@"push->GRMenuViewController?NO"
//@"push->GRMenuViewController"
//@"present->GRLoginViewController?NO"
+ (void)open:(NSString *)url params:(NSDictionary *)params completed:(GRBlankBlock)block {
    if (url.length) {
        NSRange preRange = [url rangeOfString:@"->"];
        NSRange sufRange = [url rangeOfString:@"?"];
        NSString *openType = [url substringWithRange:NSMakeRange(0, preRange.location)];
        NSString *className = [url substringWithRange:NSMakeRange(preRange.location + preRange.length, (sufRange.length ? sufRange.location : url.length) - (preRange.location + preRange.length))];
        NSString *animatedType = sufRange.length ? [url substringWithRange:NSMakeRange(sufRange.location + sufRange.length , url.length - (sufRange.location + sufRange.length))] : nil;
        Class class = NSClassFromString(className);
        if (class && [class isSubclassOfClass:[UIViewController class]]) {
            UIViewController *vc = [[class alloc] init];
            if (vc) {
                unsigned int count;
                objc_property_t* props = class_copyPropertyList(class, &count);
                for (NSString *key in params.allKeys) {
                    if (params[key]) {
                        BOOL isMatched = NO;
                        for (int i = 0; i < count; i++) {
                            objc_property_t property = props[i];
                            const char * name = property_getName(property);
                            NSString *propertyName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
                            if ([propertyName isEqualToString:key]) {
                                isMatched = YES;
                                const char * attributesChar = property_getAttributes(property);
                                NSString *attributesString = [NSString stringWithCString:attributesChar encoding:NSUTF8StringEncoding];
                                NSArray * attributesArray = [attributesString componentsSeparatedByString:@","];
                                NSString *classAttribute = [attributesArray objectAtIndex:0];
                                NSString * propertyClassString = [classAttribute substringWithRange:NSMakeRange(3, classAttribute.length - 1 - 3)] ;
                                Class propertyClass = NSClassFromString(propertyClassString);
                                if (propertyClass && [params[key] isKindOfClass:propertyClass]) {
                                    [vc setValue:params[key] forKey:key];
                                } else {
                                    [NSException raise:@"GRRouterParamsError" format:@"param:value of (%@) isn't kind of class (%@) but (%@)", key, propertyClassString, NSStringFromClass([params[key] class])];
                                }
                                break;
                            }
                      }
                        if (!isMatched) {
                             [NSException raise:@"GRRouterParamsError" format:@"param:key named (%@) doesn't exist in class (%@)", key, className];
                            return;
                        }
                  }
              }
                free(props);
                if ([openType isEqualToString:@"push"]) {
                    [self pushViewController:vc animated:([animatedType isEqualToString:@"YES"] || [animatedType isEqualToString:@"NO"]) ? animatedType.boolValue : YES];
                } else if ([openType isEqualToString:@"present"]) {
                    [self presentViewController:vc animated:[animatedType isEqualToString:@"NO"] ? NO : YES  completion:block];
                } else {
                    [NSException raise:@"GRRouterOpenTypeError" format:@"openType:(%@) doesn't exist", openType];
                }
            } else {
                [NSException raise:@"GRRouterClassError" format:@"class:(%@) can't init", className];
            }
        } else {
            [NSException raise:@"GRRouterClassError" format:@"class:(%@) doesn't exist or isn't subclass of UIViewController", className];
        }
    }
}

+ (void)open:(NSString *)url params:(NSDictionary *)params {
    [self open:url params:params completed:nil];
}


@end

原理

+ (void)open:(NSString *)url params:(NSDictionary *)params {
   [self open:url params:params completed:nil];
}
例如:  [GRRouter open:@"push->GRMenuViewController?NO" params:@{@"shop":_shop]}];

首先把字符串url @"push->GRMenuViewController?NO"根據(jù) '->' '?' (?可以省略) 解析分隔成 openType:@"push",className:@"GRMenuViewController"animatedType:@"NO", 然后利用runtime方法中的NSClassFromString()得到類(lèi)Class:GRMenuViewController 并實(shí)例化一個(gè)對(duì)象,接著通過(guò)runtime拿到類(lèi)對(duì)象GRMenuViewController里的屬性列表,當(dāng)params字典里的某個(gè)key的值匹配上了屬性列表里的一個(gè)屬性名字,接著通過(guò)runrime獲取該屬性的描述,解析出屬性的類(lèi)型如果屬性類(lèi)型與params key對(duì)應(yīng)的值(對(duì)象)的類(lèi)型相同,就通過(guò)KVC將這個(gè)key的值賦予到GRMenuViewControlle 實(shí)例對(duì)象的對(duì)應(yīng)屬性上
最后我們拿到了合適的跳轉(zhuǎn)發(fā)起者,并把GRMenuViewControlle實(shí)例對(duì)象push了出去

- (UIViewController *)hostViewController {
    if (self.hostBlock) {
        _hostViewController = self.hostBlock();
    }
    return _hostViewController;
}

謝謝觀看

水平有限,若有錯(cuò)誤,請(qǐng)多指正

git地址:https://github.com/Assuner-Lee/GRRouter.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容