Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. //
  2. // UIBarButtonItem+Badge.swift
  3. // PiGuardMobile
  4. //
  5. // Created by Stefano Vettor on 12/04/16.
  6. // Copyright © 2016 Stefano Vettor. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. extension CAShapeLayer {
  12. private func drawCircleAtLocation(location: CGPoint, withRadius radius: CGFloat, andColor color: UIColor, filled: Bool) {
  13. fillColor = filled ? color.CGColor : UIColor.whiteColor().CGColor
  14. strokeColor = color.CGColor
  15. let origin = CGPoint(x: location.x - radius, y: location.y - radius)
  16. path = UIBezierPath(ovalInRect: CGRect(origin: origin, size: CGSize(width: radius * 2, height: radius * 2))).CGPath
  17. }
  18. }
  19.  
  20. private var handle: UInt8 = 0;
  21.  
  22. extension UIBarButtonItem {
  23.  
  24. private var badgeLayer: CAShapeLayer? {
  25. if let b: AnyObject = objc_getAssociatedObject(self, &handle) {
  26. return b as? CAShapeLayer
  27. } else {
  28. return nil
  29. }
  30. }
  31.  
  32. func addBadge(number number: Int, withOffset offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.redColor(), andFilled filled: Bool = true) {
  33. guard let view = self.valueForKey("view") as? UIView else { return }
  34.  
  35. badgeLayer?.removeFromSuperlayer()
  36.  
  37. // Initialize Badge
  38. let badge = CAShapeLayer()
  39. let radius = CGFloat(7)
  40. let location = CGPoint(x: view.frame.width - (radius + offset.x), y: (radius + offset.y))
  41. badge.drawCircleAtLocation(location, withRadius: radius, andColor: color, filled: filled)
  42. view.layer.addSublayer(badge)
  43.  
  44. // Initialiaze Badge's label
  45. let label = CATextLayer()
  46. label.string = "\(number)"
  47. label.alignmentMode = kCAAlignmentCenter
  48. label.fontSize = 11
  49. label.frame = CGRect(origin: CGPoint(x: location.x - 4, y: offset.y), size: CGSize(width: 8, height: 16))
  50. label.foregroundColor = filled ? UIColor.whiteColor().CGColor : color.CGColor
  51. label.backgroundColor = UIColor.clearColor().CGColor
  52. label.contentsScale = UIScreen.mainScreen().scale
  53. badge.addSublayer(label)
  54.  
  55. // Save Badge as UIBarButtonItem property
  56. objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  57. }
  58.  
  59. func updateBadge(number number: Int) {
  60. if let text = badgeLayer?.sublayers?.filter({ $0 is CATextLayer }).first as? CATextLayer {
  61. text.string = "\(number)"
  62. }
  63. }
  64.  
  65. func removeBadge() {
  66. badgeLayer?.removeFromSuperlayer()
  67. }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement