我正在参加一个为期30天的课程来学习SWIFT 4.2,入门项目有一个表格视图来展示30个应用程序,每天一个。因此,有特定日期的故事板。
这是代码:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var dataModel = NavModel.getDays()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: nil, action: nil)
}
// MARK: uitableview delegate and datasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print ("This is dataModel.count: ", dataModel.count)
return dataModel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ContentTableViewCell
cell.data = dataModel[indexPath.row]
print(cell.data!)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dayCount = dataModel[indexPath.row].dayCount
print("This is dayCount: ", dayCount)
let initViewController = UIStoryboard(name: "Day(dayCount)", bundle: nil).instantiateInitialViewController()
self.navigationController?.pushViewController(initViewController!, animated: true)
}
}
如何更新此代码片段:
let initViewController = UIStoryboard(name: "Day(dayCount)", bundle: nil).instantiateInitialViewController()
以防止应用程序在找不到尚未存在的特定情节提要时崩溃?
这是NavModel.swift的代码:
import UIKit
class NavModel {
var dayCount: Int
var title: String
var color: UIColor
init(count: Int, title: String, color: UIColor) {
self.dayCount = count
self.title = title
self.color = color
}
class func getDays() -> [NavModel] {
var model = [NavModel]()
for i in 1...30 {
let nav = NavModel(count: i, title: "Day (i)", color: UIColor.randomFlatColor())
model.append(nav)
}
return model
}
}
您无法阻止该代码崩溃。找不到引用的情节提要是一个无法捕获的致命错误。
在测试过程中,你想了解的是一个不是捆绑包的故事板。
适当的解决方案是更改数据模型,使其仅包含您有序列图的数据。即,如果今天是第10天,那么NavModel.getDays()
应该只返回10个数据项。
I会将NavModel
重写为:
import UIKit
struct NavModel {
let dayNumber: Int
var title: String {
get {
return "Day (dayNumber)"
}
}
let color: UIColor
static func getDays(count: Int) -> [NavModel] {
var model = [NavModel]()
for i in 1...count {
model.append(NavModel(dayNumber: i, color: UIColor.randomFlatColor()))
}
return model
}
}
然后创建模型,例如NavModel.getDays(count:10)