iOS 万能跳转,支持参数
2017-11-21 本文已影响263人
为之则易ing
需求:开发中会遇到跳转各种页面。常见的:消息,推送,列表。这类需求一般是在项目中不能写死跳转到相应界面,而是由后台返回相应的数据决定跳转到相应的界面。
解决:
万能跳转原理,首先根据后台返回的类名,生成相应的viewController
Class class = NSClassFromString(className);//className 类名字符串
if (class) {
UIViewController *vc = [[class alloc] init];
[self pushViewController:vc params:params animated:animated];
}
其次,有些界面我们可能需要传入不同的参数,可以借助MJExtension中NSObject+MJKeyValue中的方法mj_setKeyValues。
if (viewController) {
if (params) {//相应的参数
[viewController mj_setKeyValues:params];
}
[self pushViewController:viewController animated:animated];
}
当然我们也可以不用MJExtension(注意:参数一定要正确,否则可能引起崩溃除非重写了 -(void)setValue:(id)value forUndefinedKey:(NSString *)key方法)
if (params) {//相应的参数
[viewController setValuesForKeysWithDictionary:params];
}
[self pushViewController:viewController animated:animated];
}
源码:
//
// UINavigationController+Addtion.m
// KKDCRM
//
// Created by xuliying on 2017/9/5.
// Copyright © 2017年 zyg. All rights reserved.
//
#import "UINavigationController+Addtion.h"
#import "MJExtension.h"
@implementation UINavigationController (Addtion)
-(void)pushViewController:(UIViewController *)viewController params:(NSDictionary *)params animated:(BOOL)animated{
if (viewController) {
if (params) {//相应的参数
[viewController mj_setKeyValues:params];
// [viewController setValuesForKeysWithDictionary:params];
}
[self pushViewController:viewController animated:animated];
}
}
-(void)pushViewControllerWithClassName:(NSString *)className params:(NSDictionary *)params animated:(BOOL)animated{
if (className) {
Class class = NSClassFromString(className);//className 类名字符串
if (class) {
UIViewController *vc = [[class alloc] init];
[self pushViewController:vc params:params animated:animated];
}
}
}
@end