在一般的開(kāi)發(fā)過(guò)程中翘贮,跳轉(zhuǎn)頁(yè)面只需要初始化需要跳轉(zhuǎn)的頁(yè)面,隨即用模態(tài)跳轉(zhuǎn)或者使用導(dǎo)航欄跳轉(zhuǎn)。
一般情況下歹颓,我們都是直接初始化相應(yīng)的控制器坯屿,然后實(shí)現(xiàn)跳轉(zhuǎn)。當(dāng)如果一個(gè)頁(yè)面上按鈕很多巍扛,比如tableview上每個(gè)row跳轉(zhuǎn)的頁(yè)面都不一樣领跛,這種方式就比較繁瑣了。
OC
OneViewController *vc = [[OneViewController alloc]init];
self.navigationController pushViewController:vc animated:YES];
Swift
let vc = OneViewController()
self.navigationController?.pushViewController(vc, animated: true)
有時(shí)候我們?cè)谕粋€(gè)頁(yè)面上添加了很多的按鈕撤奸,每個(gè)按鈕跳轉(zhuǎn)的類都不一樣吠昭,這時(shí)候我們就需要?jiǎng)討B(tài)加載控制器,可以將這些控制器的類名放進(jìn)數(shù)組里胧瓜。(注:這種方式是不能傳遞參數(shù)的)
OC
NSMutableArray *MainBusinessArr = [NSMutableArray array];
[MainBusinessArr addObject:@{@"title":@"業(yè)務(wù)聯(lián)系人",@"icon":@"聯(lián)系人",@"viewController":@"Business_contacts_ListViewController"}];
NSString *ControllerStr = [[MainBusinessArr objectAtIndex:indexPath.row] objectForKey:@"viewController"];
UIViewController* viewController = [[NSClassFromString(ControllerStr) alloc] init];
[self.navigationController pushViewController:viewController animated:YES];
Swift
var ListArr:NSMutableArray = []
ListArr.add(["name":"添加聯(lián)系人","image":"bm_addclient","viewController":"ContactAddViewController"])
let dic:[String:String] = ListArr.object(at: indexPath.row) as! [String:String]
// 獲取跳轉(zhuǎn)的類名
let targetVC:String = dic["viewController"]!
//獲取命名空間
var NameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String
// 將Bunldle Identifier中的“-”改成“_”
NameSpace = NameSpace?.replacingOccurrences(of: "-", with: "_")
let clsName = NameSpace! + "." + targetVC
let model = NSClassFromString(clsName) as! UIViewController.Type
let vc = model.init()
self.navigationController?.pushViewController(vc, animated: true)
項(xiàng)目命名空間中不能存在“-”字符矢棚,不然會(huì)沒(méi)辦法解析,無(wú)法跳轉(zhuǎn)對(duì)應(yīng)的類府喳。