ios - 如何在创建的 UIViewController 中执行另一个 UIViewController 的函数

标签 ios swift uitableview uiviewcontroller

我有 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()
    }
}

这是一张图片,所以看看我为什么要这样做:

enter image description here

感谢您的宝贵时间!

最佳答案

您有两个选择:

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/

相关文章:

iOS 7 - 禁用 UITabBarItem 色调颜色

iOS Facebook Messenger,打开并完成任务后自动关闭链接

iOS - 继承是如何工作的?

ios - ARKit 平面,上面有现实世界的物体

ios - CoreBluetooth - 后台模式下的 didDiscoverPeripheral 在没有 LightBlue 的情况下不会被调用

iphone - heightForRowAtIndexPath : was executed before cell is show?

ios - 从 Firebase 下载 pdf 并将其本地存储在 iOS 上

ios - 如果互联网连接丢失,如何禁用整个应用程序?

iOS View 和 UI/UX

ios - iOS 中的水平可 ScrollView ?