開發(fā)中搓幌,我們有一些頁(yè)面為固定數(shù)據(jù)的列表頁(yè)杆故。點(diǎn)擊跳往不同的頁(yè)面。
這樣的需求溉愁,方法有很多处铛,列舉三個(gè)常用的方式,最推薦第三個(gè)!
數(shù)據(jù)源:定義一個(gè)套字典的數(shù)組撤蟆,跳轉(zhuǎn)只用到標(biāo)題和類名篙贸,可視需求添加其他字段
var listDic = [["vcName":"FirstVC",
"vcTitle":"頁(yè)面一"],
["vcName":"SecondVC",
"vcTitle":"頁(yè)面二"],
["vcName":"ThirdVC",
"vcTitle":"頁(yè)面三"]]
方式一:根據(jù)點(diǎn)擊行數(shù)進(jìn)行判斷,跳不同的頁(yè)面(沒啥技術(shù)含量)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
let vc = FirstVC()
self.navigationController?.pushViewController(vc, animated: true)
case 1:
let vc = SecondVC()
self.navigationController?.pushViewController(vc, animated: true)
case 2:
let vc = ThirdVC()
self.navigationController?.pushViewController(vc, animated: true)
default:
return
}
}
方式二:根據(jù)內(nèi)容判斷點(diǎn)擊的是哪一個(gè)數(shù)據(jù)枫疆,再跳往下一個(gè)頁(yè)面(也沒啥技術(shù)含量)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let vcName = listDic[indexPath.row]["vcTitle"] else { return print("error") }
if vcName == "頁(yè)面一" {
let firstVC = FirstVC()
firstVC.title = vcName
self.navigationController?.pushViewController(firstVC, animated: true)
} else if vcName == "頁(yè)面二" {
let secondVC = SecondVC()
secondVC.title = vcName
self.navigationController?.pushViewController(secondVC, animated: true)
} else if vcName == "頁(yè)面三" {
let thirdVC = ThirdVC()
thirdVC.title = vcName
self.navigationController?.pushViewController(thirdVC, animated: true)
}
}
方式三:根據(jù)類名自動(dòng)創(chuàng)建類爵川,OC中映射。在swift中不能直接用息楔,因?yàn)槎嗔艘粋€(gè)命名空間的概念
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 數(shù)據(jù)源: listData = ["SnapDemoVC", "AutomaticVC"]
// 1. 獲取去命名空間,由于項(xiàng)目肯定有info.plist文件所有可以機(jī)型強(qiáng)制解包.
guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { return print("沒有獲取到命名空間")}
print("命名空間為:",nameSpace)
// 2. 拼寫命名空間.類名(比如)
let vcName = nameSpace + "." + listDic[indexPath.row]["vcName"]!
print("文件名:", vcName)
// 3. 將類名轉(zhuǎn)化成類
guard let classType = NSClassFromString(vcName) else { return print("\"\(vcName)\" is not class") }
// 4. 將類轉(zhuǎn)化成UIViewController
guard let vcType = classType as? UIViewController.Type else { return print("\"\(vcName)\" is not UIViewController") }
// 5. 用vcType實(shí)例化對(duì)象
let vc = vcType.init()
// 6. 跳轉(zhuǎn)
navigationController?.pushViewController(vc, animated: true)
}
優(yōu)點(diǎn)很多寝贡,最大優(yōu)勢(shì)是,想增值依、刪圃泡、改頁(yè)面跳轉(zhuǎn)時(shí),只需要管理數(shù)據(jù)源愿险,不需要改didSelectRow里面任何代碼颇蜡,非常簡(jiǎn)潔,也便于維護(hù)辆亏。