我在很多ViewController的导航栏上有一个购物车。该值在购物车上正确显示,并有增减。问题是,当我在导航栏中单击“上一步”按钮时,上一个viewController cart值就消失了。
import UIKit
import Foundation
var navCartLabel = UILabel()
家庭控制器
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)")
}
})
}
})
}
}
视图加载
override func viewDidLoad() {
super.viewDidLoad()
setupHomeNavBarBtn()
}
将出现视图
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)
}
}
最佳答案
尝试将setupHomeNavBarBtn
移到viewWillAppear
内,例如:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//... your other stuff here...
self.setupHomeNavBarBtn()
}
关于ios - swift :在NavigationItem中,当我使用NavigationBar中的“后退”按钮返回到CartValue时,它消失了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47854155/