我不确定这是否可行,或者我是否打算使用错误的方式,但是...
我有一个电子商务应用程序。您可以将产品添加到购物车。我想在购物车上显示徽章,并在购物车中显示商品数量。
但是,我的购物车处于静态结构中,需要更新tabbarController。
如何让这两个彼此之间进行交流?
购物车
import Foundation
struct Cart {
static var items: [CartItem] = []
static func updateItem(id:Int,increment:Int){
var itemAdded = false
for (index, item) in items.enumerated() {
if item.fabric.id == id {
item.quantity = item.quantity+increment
if item.quantity <= 0 {
items.remove(at: index)
}
itemAdded = true
}
}
if !itemAdded {
// fabric not in cart
// add it
for item in API.fabrics{
if item.id == id{
items.append(CartItem(fabric: item, quantity: 1))
return
}
}
}
// AREA IN QUESTION
// let MainTabBarController = AppDelegate
// if let tabItems = tabBarController?.tabBar.items{
//
// }
}
}
class CartItem{
let fabric: Fabric
var quantity: Int
init(fabric: Fabric,
quantity: Int){
self.fabric = fabric
self.quantity = quantity
}
}
应用程序委托
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIApplication.shared.statusBarStyle = .lightContent
window = UIWindow(frame: UIScreen.main.bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let MainTabBarController = storyboard.instantiateViewController(withIdentifier: "MainTabBarController")
window?.rootViewController = MainTabBarController
window?.makeKeyAndVisible()
return true
}
答案 0 :(得分:2)
您可以使用NSNotificationcenter.post(_ notification: Notification),因此每次将商品添加到购物车时,您都会发布通知,而您的TabController
可以订阅并处理该通知。像这样:
import NotificationCenter
import UIKit
struct Cart {
func add(item: Int) {
// Your code to handle stuff...
let numberOfItems = item
let notification = Notification(name: Notification.Name(rawValue: "addItem"), object: nil, userInfo: ["numberOfItems":numberOfItems])
NotificationCenter.default.post(notification)
}
}
class YourTabBarController: UITabBarController {
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(handleAddItem), name: NSNotification.Name(rawValue: "addItem"), object: nil)
}
@objc func handleAddItem(notification: Notification) {
// increment badge value
tabBar.items?.first?.badgeValue = "\(notification.userInfo!["numberOfItems"]!)"
}
}
当然,您可以执行相同的操作来删除项目和所需的所有其他内容。
答案 1 :(得分:1)
如果tabbarcontroller是rootviewcontroller
if let tabbarController = UIApplication.shared.keyWindow?.rootViewController as? MainTabBarController{
tabbarControllertabBar.items[indexpOfTabbarItem]!.badgeValue = value
}
如果rootviewcontroller是tabbarcontroller的Navigationcontroller:
if let tabbarNavigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController, let tabbarController = tabbarNavigationController.viewControllers.first as? MainTabBarController {
tabbarControllertabBar.items[indexpOfTabbarItem]!.badgeValue = value
}