0

背景

我按照本教程实现了自定义徽章: http: //www.stefanovettor.com/2016/04/30/adding-badge-uibarbuttonitem/

问题

徽章层位于 UITabBarItem 图像下方。如何将它放在图像的顶部?我尝试使用 view.layer.insertSublayer 最后插入徽章层,但没有运气。

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)
}

在此处输入图像描述

4

0 回答 0