Advertisement
Guest User

Untitled

a guest
May 19th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. extension CAShapeLayer {
  2. func drawCircleAtLocation(location: CGPoint, withRadius radius: CGFloat, andColor color: UIColor, filled: Bool) {
  3. fillColor = filled ? color.cgColor : UIColor.white.cgColor
  4. strokeColor = color.cgColor
  5. let origin = CGPoint(x: location.x - radius, y: location.y - radius)
  6. path = UIBezierPath(ovalIn: CGRect(origin: origin, size: CGSize(width: radius * 2, height: radius * 2))).cgPath
  7. }
  8. }
  9.  
  10. private var handle: UInt8 = 0;
  11.  
  12. extension UIBarButtonItem {
  13. private var badgeLayer: CAShapeLayer? {
  14. if let badge: AnyObject = objc_getAssociatedObject(self, &handle) as AnyObject? {
  15. return badge as? CAShapeLayer
  16. } else {
  17. return nil
  18. }
  19. }
  20.  
  21. func addBadge(number: Int, withOffset offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.red, andFilled filled: Bool = true) {
  22. guard let view = self.value(forKey: "view") as? UIView else { return }
  23.  
  24. badgeLayer?.removeFromSuperlayer()
  25.  
  26. var badgeWidth = 8
  27. var numberOffset = 4
  28.  
  29. if number > 9 {
  30. badgeWidth = 12
  31. numberOffset = 6
  32. }
  33.  
  34. // Initialize Badge
  35. let badge = CAShapeLayer()
  36. let radius = CGFloat(7)
  37. let location = CGPoint(x: view.frame.width - (radius + offset.x), y: (radius + offset.y))
  38. badge.drawCircleAtLocation(location: location, withRadius: radius, andColor: color, filled: filled)
  39. view.layer.addSublayer(badge)
  40.  
  41. // Initialiaze Badge's label
  42. let label = CATextLayer()
  43. label.string = "\(number)"
  44. label.alignmentMode = CATextLayerAlignmentMode.center
  45. label.fontSize = 11
  46. label.frame = CGRect(origin: CGPoint(x: location.x - CGFloat(numberOffset), y: offset.y), size: CGSize(width: badgeWidth, height: 16))
  47. label.foregroundColor = filled ? UIColor.white.cgColor : color.cgColor
  48. label.backgroundColor = UIColor.clear.cgColor
  49. label.contentsScale = UIScreen.main.scale
  50. badge.addSublayer(label)
  51.  
  52. // Save Badge as UIBarButtonItem property
  53. objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  54. }
  55.  
  56. func updateBadge(number: Int) {
  57. if let text = badgeLayer?.sublayers?.filter({ $0 is CATextLayer }).first as? CATextLayer {
  58. text.string = "\(number)"
  59. }
  60. }
  61.  
  62. func removeBadge() {
  63. badgeLayer?.removeFromSuperlayer()
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement