【发布时间】:2020-12-27 17:58:32
【问题描述】:
我有一个带有 tableView 的 viewController,另一个 viewController 包含我试图传递给 tableView 的数据。为了向 tableView 添加条目,我使用了 segues,但 segues 的问题是它们不会永久更新 tableView。他们只是创建 ViewController 的一个实例并在那里添加条目,但原始对象保持不变。两个 ViewController 都是标签栏控制器的一部分。我想要的是永久更新表格。意思是,我希望能够导航到定义表的 viewController 并查看已添加的条目。这是带有 tableView 的 viewController 的代码:
import UIKit
class FavoritesViewController: UIViewController {
public 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()
}
}
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 中的 tableView 的方式:
class MainViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate{
public var shopName:String?
// there are also many other vars, but they're irrelevant
public var favoritesDestinationVC = FavoritesViewController()
// prepares the data for the segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToFavs" {
favoritesDestinationVC = segue.destination as! FavoritesViewController
if let newShopName = shopName {
favoritesDestinationVC.shops.append(newShopName)
}
}
}
}
但是,当我将条目添加到表中时,segue 会创建一个 FavoritesViewController 的实例,在此处添加该条目,然后在弹出窗口中显示它,如下所示:
但是当我关闭此窗口时,更改消失(tableView 保持不变;3 次“Hello World”)。
我希望在关闭此窗口后将更改保存在 tableView 中。关于如何做到这一点的任何想法?关于如何使这些更改永久化?
【问题讨论】:
标签: ios swift uitableview