swift 如何在导航栏中的购物车 UIBarButton 上添加标签

how to add label on cart UIBarButton in NavigationBar in swift

我正在研究食品订购应用程序原型。我遇到一个问题,即如何在 BarButton 上添加数量标签。我找不到这样做的方法。谁能帮帮我?

这是设计

private var handle: UInt8 = 0

public func addBadge(number: Int, withOffset offset: CGPoint = CGPoint.zero, andBackgroundColor color: UIColor, strokeColor: UIColor,textColor:UIColor) {
        guard let view = self as? UIView else { return }

        badgeLayer?.removeFromSuperlayer()

        // Initialize Badge
        let badge = CAShapeLayer()
        let radius = CGFloat(8)
        let location = CGPoint(x: view.frame.width - (radius + offset.x), y: (radius + offset.y))
        badge.drawCircleAtLocation(location: location, withRadius: radius, andColor: color, stokColor: strokeColor)
        view.layer.addSublayer(badge)

        // Initialiaze Badge's label
        let label = CATextLayer()
        label.string = "\(number)"
        label.alignmentMode = kCAAlignmentCenter
        if number > 9 {
            label.fontSize = 9
            label.font = UIFont(name:"HelveticaNeue-Bold", size: 9)!
            label.frame = CGRect(origin: CGPoint(x: location.x - 5, y: offset.y+2), size: CGSize(width: 10, height: 16))
        }else{
            label.fontSize = 11
            label.font = UIFont(name:"HelveticaNeue-Bold", size: 11)!
            label.frame = CGRect(origin: CGPoint(x: location.x - 5, y: offset.y+1), size: CGSize(width: 10, height: 16))
        }
        label.foregroundColor = textColor.cgColor
        label.backgroundColor = UIColor.clear.cgColor
        label.contentsScale = UIScreen.main.scale
        badge.addSublayer(label)

        // Save Badge as UIBarButtonItem property
        objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }


extension CAShapeLayer {
    func drawCircleAtLocation(location: CGPoint, withRadius radius: CGFloat, andColor color: UIColor,stokColor:UIColor) {
        fillColor = color.cgColor
        strokeColor = stokColor.cgColor
        let origin = CGPoint(x: location.x - radius, y: location.y - radius)
        path = UIBezierPath(ovalIn: CGRect(origin: origin, size: CGSize(width: radius * 2, height: radius * 2))).cgPath
    }
}

那么您可以将其用作:

yourBtn.addBadge(number: 0, withOffset: CGPoint(x: -3, y: -3), andBackgroundColor: UIColor.red, strokeColor: UIColor.white, textColor:
            UIColor.white)