【发布时间】:2020-12-21 18:42:37
【问题描述】:
我正在尝试通过从另一个 viewController 的 segue 发送数据,将单元格添加到 viewController 中的 tableView。
class FavoritesViewController: UIViewController {
var shops = [
"hello world",
"hello world",
"hello world"
]
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
table.reloadData()
}
}
//protocol FavoritesDelegate: class {
// func add(_ shopName: String)
//}
extension FavoritesViewController: UITableViewDelegate, UITableViewDataSource{
func add(_ shopName: String) {
print(shopName)
shops.append(shopName)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
cell.textLabel?.text = shops[indexPath.row]
return cell
}
// define the action. In this case "delete"
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
// do the actual deleting
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableView.beginUpdates()
shops.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
}
}
}
这是另一个 viewController 中的函数调用(准备):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
favoritesDestinationVC = segue.destination as! FavoritesViewController
favoritesDestinationVC.add(shopName!)
}
我知道导致错误的原因(favoritesDestinationVC 创建了一个 tableView 为 nil 的新实例),但我不知道如何解决它。关于如何以这种方式向 tableView 添加条目(然后更新表格)而不会使我的应用崩溃的任何想法?
【问题讨论】:
-
使用闭包作为 UI 实例的回调。在另一个视图控制器中完成您的工作,在返回第一个视图控制器之前,只需调用第一个 VC 的回调即可。您提供的代码不足以向您建议一种有效的方法。您最好分享与您的问题相关的所有代码。
-
我更新了代码。
标签: ios swift tableview segue reloaddata