ios - 当无法找到故事板或尚未创建故事板时,如何防止 SWIFT 4.2 运行时错误?
问题描述
我正在做一个为期 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 个数据项。
我会重写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)
推荐阅读
- c# - OpenGL某些VertexBuffers不渲染
- haskell - 如何将 (Integer, Int, Int ) 转换为 Day。无法将预期类型 'Day' 与实际类型 '(Integer, Int, Int)' 匹配
- google-app-engine - 使用 appengineRun 运行 Spring Boot webapp
- r - plot.window(...) 中的错误:需要有限的“xlim”值
- android - Android System Webview 上次更新后代理设置停止工作
- javascript - 滑块未显示所有图像
- python-3.x - 检索源页面后,Scrapy Crawler 多个域完成且没有错误
- amazon-web-services - AWS 上的 kubernetes 在 pod 中获取区域名称
- css - CSS 表单对齐按钮和复选框
- reactjs - 如何在 react-boilerplate 中添加 jsx 文件?