[英]UITableView wont refresh after adding a new entry
從我的原始視圖controller(BudgientViewController)我有一個模態視圖Z594C103F2C6E04C3D8AB059F059F031E0C1AZ在POPS上pops pops pops pops pops pops上升。 用戶選擇了一個新類別並且 AddCategory() 被解除。 我嘗試通過在 viewWillAppear()、viewDidAppear 中添加 self.tableView.reloadData() 以及作為完成處理程序來刷新 BudgetViewController() 中的 UITableView,但它仍然拒絕刷新 UITableView。
class BudgetViewController: UIViewController {
var budgetData: [Transaction] = [
Transaction(title: "Groceries", dateInfo: "0% out of spent", image:UIImage.groceriesIcon, amount: 4512)
]
func didTapAddCategory(_ button: UIButton) {
let modalViewController = AddCategory()
modalViewController.addCategoryCompletion = {
self.tableView.reloadData()
}
present(modalViewController, animated: false, completion: modalViewController.addCategoryCompletion)
}
override func viewDidAppear(_ animated: Bool) {
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.budgetData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CategoryCell.identifier) as? CategoryCell else { return UITableViewCell() }
let data = budgetData[indexPath.row]
cell.populate(with: data)
cell.spentLabel.text = "-"
cell.rangeLabel.text = ""
return cell
}
class AddCategory: UIViewController{
let budgetVC = BudgetViewController()
var addCategoryCompletion: (() -> Void)?
@objc func prin(){
budgetVC.budgetData.append(Transaction(title: textField.text ?? "", dateInfo: "n", image: UIImage.gymIcon, amount: 12, annualPercentageRate: 12, trailingSubText: "12"))
self.dismiss(animated: false, completion: addCategoryCompletion)
print("selected")
print(budgetVC.budgetData)
}
let categoryTF: UITextField = {
let tf = UITextField()
tf.placeholder = " Category name"
tf.font = UIFont.systemFont(ofSize: 14)
return tf
}()
let saveButton: UIButton = {
let button = UIButton()
button.setTitle("Save", for: .normal)
button.layer.cornerRadius = 7
button.addTarget(self, action: #selector(prin), for:.touchUpInside)
return button
}()
}
如前所述,您從BudgetVC number 1
創建AddcategoryVC
,並在其中創建BudgetVC number 2
。 因此,為BudgetVC number 2
調用重新加載數據沒有任何作用。
使用回調是最常見的解決方案:使用
var addCategoryCompletion: ((Transaction) -> Void)?
並刪除
let budgetVC = BudgetViewController()
在AddCategory
里面
在didTapAddCategory
中設置完成
let modalViewController = AddCategory()
modalViewController.addCategoryCompletion = { newTransaction in
self.budgetData.append(newTransaction)
self.tableView.reloadData()
}
最后在prin
方法中的dismiss action中調用這個完成回調
let newTransaction = Transaction(title: textField.text ?? "",
dateInfo: "n",
image: UIImage.gymIcon,
amount: 12,
annualPercentageRate: 12,
trailingSubText: "12")
self.dismiss(animated: false, completion: {
self.addCategoryCompletion?(newTransaction)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.