0

Background

I followed this tutorial to achieve custom badges: http://www.stefanovettor.com/2016/04/30/adding-badge-uibarbuttonitem/

Problem

The badge layer is placed underneath the UITabBarItem image. How do I place it on top of the image? I tried to insert the badge layer last with view.layer.insertSublayer but no luck.

func addBadge(number number: Int, withOffset offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.redColor(), andFilled filled: Bool = true) {
    guard let view = self.valueForKey("view") as? UIView else { return }

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

    // Initialiaze Badge's label
    let label = CATextLayer()
    label.string = "\(number)"
    label.alignmentMode = kCAAlignmentCenter
    label.fontSize = 13
    label.frame = CGRect(origin: CGPoint(x: location.x - 5, y: offset.y + 1), size: CGSize(width: 9, height: 16))
    label.foregroundColor = filled ? UIColor.whiteColor().CGColor : color.CGColor
    label.backgroundColor = UIColor.clearColor().CGColor
    label.contentsScale = UIScreen.mainScreen().scale
    badge.addSublayer(label)
}

enter image description here

0xRLA
  • 3,279
  • 4
  • 30
  • 42

0 Answers0