将CAShapeLayer放在UIBarItem中的UIImage之上

时间:2016-11-21 05:36:43

标签: swift uibaritem

背景

我按照本教程来实现自定义徽章: 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)
}

enter image description here

0 个答案:

没有答案