在swift中popViewController时,导航栏中的购物车计数未更新



我已经创建了带有cart的自定义导航栏及其计数,如下代码所示:如果我在所有视图控制器中调用setUpNavigationBar(),我将获得带有cart并计数的导航栏

func setUpNavigationBar(){
self.navigationController?.navigationBar.backgroundColor = CommonColor.navigationColor
self.navigationController?.navigationBar.barTintColor = CommonColor.navigationColor
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.layer.masksToBounds = false
let cartBtn: BadgeButton = BadgeButton(type: .custom)
cartBtn.setImage(#imageLiteral(resourceName: "icon55"), for: .normal)
cartBtn.addAction(for: .touchUpInside) {
print("in cart")
let signupVC = (StoryBoard.driver).instantiateViewController(identifier: "ShoppingCartVC") as! ShoppingCartVC
self.navigationController?.pushViewController(signupVC, animated: true)
}
cartBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
let cartQty = UserDefaults.standard.value(forKey: "cartCount")
cartBtn.badgeText = cartQty as? String
let btnCart = UIBarButtonItem(customView: cartBtn)
self.navigationItem.setRightBarButton(btnCart, animated: true)
}
func setBadgeCountForCart(with : String?){
let badge = self.navigationItem.rightBarButtonItems?.map({$0.customView}).filter({$0 is BadgeButton}).first as? BadgeButton
badge?.badgeText = with
}

但在ShoppingCartVC中,我不想要导航栏,所以我没有在ShoppingCartVC视图中调用setUpNavigationBar并加载

因此,如果从购物车中删除产品,并单击ShoppingCartVC中的返回按钮,则购物车Conut不会在弹出的视图控制器中更新

删除产品后,我更新了cartCount,如下所示:

class ShoppingCartVC: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.navigationBar.isHidden = true
self.serviceCall()
}
func serviceCall(){
self.cartDB = ShoppingCartDetaModel(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())

UserDefaults.standard.set(self.cartDB?.result?.cart?.total_item, forKey: "cartCount")
self.setUpNavigationBar()
}
@IBAction func back(_ sender: UIButton){
self.navigationController?.navigationBar.isHidden = false
self.serviceCall()
UserDefaults.standard.set(self.cartDB?.result?.cart?.total_item, forKey: "cartCount")
self.setUpNavigationBar()
self.navigationController?.popViewController(animated: true)
}
}

我该在哪里换车,请帮

导航返回后,需要使用更新的数量更新BadgeButton及其text属性。你可以使用不同的方法来实现这一点。最简单且不太干净的方法是在viewWillAppear方法中调用self.setUpNavigationBar()。更干净的方法是使用NotificationCenter类或Publisher,并在每次数量更改时发布更新。

将显示的视图:https://developer.apple.com/documentation/uikit/uiviewcontroller/1621510-viewwillappear

通知中心:https://developer.apple.com/documentation/foundation/notificationcenter

发布者:https://developer.apple.com/documentation/combine/publisher

相关内容

  • 没有找到相关文章

最新更新