要在新的ViewController中显示保存的对象数组,需要进行以下步骤:
在原始ViewController中,确保已经将对象数组保存到合适的位置。例如,可以将对象数组保存到一个全局变量、单例类或者应用程序的数据模型中。
在新的ViewController中,首先获取原始ViewController中保存的对象数组。可以通过访问全局变量、单例类或者应用程序的数据模型来获取对象数组。
在新的ViewController中,创建一个UITableView,并将其添加到视图层次结构中。确保UITableView的数据源和代理已经设置为新的ViewController。
在新的ViewController中,实现UITableView的数据源方法,以便显示对象数组中的数据。例如,可以实现tableView(_:numberOfRowsInSection:)
方法来返回对象数组的数量,实现tableView(_:cellForRowAt:)
方法来设置每行的内容。
下面是一个示例代码,演示了如何在新的ViewController中显示保存的对象数组:
// 原始ViewController
class OriginalViewController: UIViewController {
var objectArray: [Object] = [] // 对象数组
func saveObjectArray() {
// 将对象数组保存到适当的位置
// 例如,将其保存到全局变量或者应用程序的数据模型中
// objectArray = ...
}
func goToNewViewController() {
let newViewController = NewViewController()
newViewController.objectArray = objectArray // 将对象数组传递给新的ViewController
navigationController?.pushViewController(newViewController, animated: true)
}
}
// 新的ViewController
class NewViewController: UIViewController, UITableViewDataSource {
var objectArray: [Object] = [] // 接收原始ViewController传递的对象数组
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: view.bounds, style: .plain)
tableView.dataSource = self
view.addSubview(tableView)
}
// UITableViewDataSource方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
let object = objectArray[indexPath.row]
cell.textLabel?.text = object.title // 设置每行的内容
return cell
}
}
通过以上步骤,原始ViewController中保存的对象数组就能在新的ViewController中正确显示出来了。
下一篇:保存的方法运行迁移时出错