【问题标题】:how to add label on cart UIBarButton in NavigationBar in swift如何快速在导航栏中的购物车 UIBarButton 上添加标签
【发布时间】:2018-05-21 06:40:43
【问题描述】:

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

这里是设计

【问题讨论】:

  • 使用自定义视图创建 barbutton 项目没有帮助?
  • 这个链接可能对你有帮助github.com/pratik-123/FlyToCart
  • 你能展示一下设计吗?
  • 您想在按钮上添加标签吗?你可以给你的栏按钮标题。
  • 其实我想在栏按钮上方添加标签

标签: ios swift uilabel uinavigationbar uibarbuttonitem


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多