更改右栏项目swift 4上的标签文本

时间:2019-02-15 19:16:35

标签: ios swift uinavigationcontroller uinavigationbar

我在视图控制器扩展中创建了一个通用的导航方法,以在整个应用程序中在导航栏上显示,关闭和购物车项目。它会正确显示导航栏上的项目。但是导航栏右侧的购物车项目具有按钮图标和带有标签的圆形徽章图标。每当购物车中添加商品时,我都需要更新标签并增加标签数。但是标签不改变。以下是我的代码-

UIViewController扩展-

func setCartBarButtonItem() {
    let cartBarButton = UIBarButtonItem.init(customView: getCartButton())
    self.navigationItem.rightBarButtonItem = cartBarButton
}

    func getCartButton() -> UIButton{

            let frame = CGRect.init(x: UIScreen.main.bounds.width - 40, y: 14, width: 44, height:44)
            let cartButton = UIButton.init(frame: frame)
            cartButton.setImage(UIImage(named: "cart"), for: .normal)
            cartButton.addTarget(self, action: #selector(self.cartButtonTapped), for: .touchUpInside)
            let cartLabelView = UIView(frame: CGRect(x: cartButton.layer.bounds.width/2, y: 10, width: 16, height: 16))
            cartLabelView.backgroundColor = UIColor(red: 255.0/255.0, green: 234.0/255.0, blue: 41.0/255.0, alpha: 1.0)
            cartLabelView.layer.cornerRadius = 8
            cartLabelView.layer.borderWidth = 0.5
            cartLabelView.layer.borderColor = UIColor(red: 54.0/255.0, green: 54.0/255.0, blue: 54.0/255.0, alpha: 1.0).cgColor
            cartButton.addSubview(cartLabelView)

            let cartLabel = UILabel(frame: CGRect(x: cartLabelView.layer.bounds.width/3, y: 0, width: cartLabelView.layer.bounds.width, height: cartLabelView.layer.bounds.height))
            cartLabel.textColor = UIColor.black
            cartLabel.font = UIFont(name: "Arial", size: 9)
            cartLabelView.addSubview(cartLabel)
            cartLabelView.isHidden = true

                    var count = 0
                    count = getNumberOfItemInCart()
                    if count > 0 {
                        cartLabelView.isHidden = false
                        cartLabel.text = String(count)
                    }

            return cartButton
        }

在将项目添加到购物车中时调用的一个委托函数中,我调用此setCartBarButtonItem()来更新标签。但是标签不会更新。它仅显示最后一个值。

0 个答案:

没有答案