我有 2 个 UIViewController:ProductsVC 和 CartVC。在 CartVC 中,我有一个功能可以清除购物车中的所有产品。 我想要做的是,当我在 ProductsVC 中时,我从 CoreData 中删除一个产品,然后从第二个 VC(CartVC)中清除我的所有产品。所以我需要告诉该函数在那里执行。
这是我的代码:
// First VC
class ProductsViewController: UIViewController{
// Function to delete a Product from the table view and also from CoreData
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let productEntity = Constants.productEntity
let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let product = productsArray[indexPath.row]
// ----------- HERE I NEED TO TELL TO "clearAllProducts()" to be executed in the CartVC so when I click on the Cart button, there will be 0 products.
if editingStyle == .delete {
managedContext.delete(product)
do {
try managedContext.save()
} catch let error as NSError {
print(Constants.errorDeletingProduct + "\(error.userInfo)")
}
}
// fetch new data from DB and reload products table view
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: productEntity)
do {
productsArray = try managedContext.fetch(fetchRequest) as! [Product]
} catch let error as NSError {
print(Constants.errorFetchingData + "\(error.userInfo)")
}
productsTableView.reloadData()
}
}
// Second VC
class CartViewController: UIViewController {
// Clear all products from the cart
@IBAction func clearAllProducts(_ sender: Any) {
// Reset Cart tableView
productsInCartArray = [Product]()
productPricesArray = [Float]()
totalSum = 0
self.tabBarController?.tabBar.items?[1].badgeValue = String(0)
// Remove selected products from ProductsViewController
((self.tabBarController?.viewControllers![0] as! UINavigationController).topViewController as! ProductsViewController).selectedProductsArray = [Product]()
((self.tabBarController?.viewControllers![0] as! UINavigationController).topViewController as! ProductsViewController).priceForSelectedProductsArray = [Float]()
((self.tabBarController?.viewControllers![0] as! UINavigationController).topViewController as! ProductsViewController).counterItem = 0
((self.tabBarController?.viewControllers![0] as! UINavigationController).topViewController as! ProductsViewController).numberOfProductsInCartLabel.text = String(0)
UIApplication.shared.applicationIconBadgeNumber = 0
cartTableView.reloadData()
}
}
这是一张图片,所以看看我为什么要这样做:
感谢您的宝贵时间!
最佳答案
您有两个选择:
1:
如果一个 View Controller 被另一个 View Controller 调用,那么您可以在被调用的 VC 中拥有一个委托(delegate)属性,并将委托(delegate)的值分配给第一个 View Controller ,然后通常调用委托(delegate)方法。例如self.delegate?.myFunc()
2:
如果您的 View Controller 不直接相关,那么您可以使用 NotificationCenter
向所有监听 View 发送通知。 根据您的情况,这个可能更合适。
关于ios - 如何在创建的 UIViewController 中执行另一个 UIViewController 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51168062/