ios - 如何快速在导航栏中的购物车 UIBarButton 上添加标签

标签 ios swift uilabel uinavigationbar uibarbuttonitem

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

这是设计 the label should be on the cart button

最佳答案

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)

关于ios - 如何快速在导航栏中的购物车 UIBarButton 上添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50443315/

相关文章:

ios - 使用 requestAccessToEntityType 时出现 BAD ACCESS 错误

ios - 使用 WatchConnectivity 获取核心数据请求

swift - '...' 的重载存在这些结果类型 : ClosedRange<Bound>, CountableClosedRange<Bound>

ios - 设置 UIView 大小以适应 subview

ios - 返回变量的所有者 - Swift

ios - 将值连接到 NSMutableDictionary 中的相同键

android - 使用 CMake 进行 cocos2d-x 项目

swift - 我可以使用可选链接为可选属性提供默认值吗?

ios - label.isHidden = false 不出现,Swift

ios - 无法在 Storyboard 上引用 UILabel