我在很多ViewController的导航栏上都有一个推车。随着增加和减少,正确显示在购物车上的值。问题是当我单击导航栏中的后退按钮时,之前的viewController购物车价值就消失了。
import UIKit
import Foundation
var navCartLabel = UILabel()
的HomeController
class HomeCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout{
func navCartDataLoad(POST_PARAMETERS: Dictionary<String, String>){
NetworkRequestAPI.postAndGet(params: POST_PARAMETERS, url: Configuration.URL_TO_ADD_CART_FOR_MAINACTIVITY) { (response, error) in
DispatchQueue.main.async(execute: {
let json: [String:Any] = response
if(!error) {
do {
} catch let error as NSError {
print(error)
}
DispatchQueue.main.async(execute: {
if let myCartText = json["cart_item_count"] as? Int {
navCartLabel.text = "\(myCartText)"
print("cart text api \(myCartText)")
}
})
}
})
}
}
viewDidLoad中
override func viewDidLoad() {
super.viewDidLoad()
setupHomeNavBarBtn()
}
viewWillAppear中
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let user_id = UserDefaults.standard.string(forKey: "user_id")
if user_id != nil {
print(" cart not nill")
navCartLabel.backgroundColor = .red
navCartLabel.textColor = .white
print("cart label value \(navCartLabel.text)")
let POST_PARAMETERS = ["user_id": user_id]
self.navCartDataLoad(POST_PARAMETERS: POST_PARAMETERS as! Dictionary<String, String>)
} else {
print("cart nil ")
navCartLabel.backgroundColor = .clear
navCartLabel.textColor = .clear
}
}
**setupNavigation Item**
func setupHomeNavBarBtn() {
let navCartBtn = UIButton()
navCartBtn.frame = CGRect(x: 0, y: 0, width: CollectionViewSize.width / 15, height: CollectionViewSize.width / 15)
navCartBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, CollectionViewSize.width / 60, 0)
navCartBtn.setImage(UIImage(named: "cart_empty"), for: .normal)
navCartBtn.contentMode = .scaleAspectFit
// navCartBtn.addTarget(self, action: #selector(navCartBtnClick), for: .touchUpInside)
navCartLabel.font = UIFont.systemFont(ofSize: CollectionViewSize.width / 40)
navCartLabel.backgroundColor = .red
navCartLabel.frame = CGRect(x: CollectionViewSize.width / 37.5, y: -(CollectionViewSize.width / 75), width: CollectionViewSize.width / 25, height: CollectionViewSize.width / 25)
navCartLabel.layer.cornerRadius = CollectionViewSize.width / 50
navCartLabel.layer.masksToBounds = true
navCartBtn.addSubview(navCartLabel)
let cartBarBtnItem = UIBarButtonItem(customView: navCartBtn)
self.navigationItem.setRightBarButtonItems([cartBarBtnItem], animated: true)
}
}
答案 0 :(得分:1)
尝试在setupHomeNavBarBtn
内移动viewWillAppear
,例如:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//... your other stuff here...
self.setupHomeNavBarBtn()
}