You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.6 KiB

6 years ago
  1. //
  2. // SSBadgeButton.swift
  3. // GMERemittance
  4. //
  5. // Created by FMI-12 on 3/27/18.
  6. // Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. class SSBadgeButton: UIButton {
  11. var badgeLabel = UILabel()
  12. var badge: String? {
  13. didSet {
  14. addBadgeToButon(badge: badge)
  15. }
  16. }
  17. public var badgeBackgroundColor = UIColor.red {
  18. didSet {
  19. badgeLabel.backgroundColor = badgeBackgroundColor
  20. }
  21. }
  22. public var badgeTextColor = UIColor.white {
  23. didSet {
  24. badgeLabel.textColor = badgeTextColor
  25. }
  26. }
  27. public var badgeFont = UIFont.systemFont(ofSize: 12.0) {
  28. didSet {
  29. badgeLabel.font = badgeFont
  30. }
  31. }
  32. public var badgeEdgeInsets: UIEdgeInsets? {
  33. didSet {
  34. addBadgeToButon(badge: badge)
  35. }
  36. }
  37. override init(frame: CGRect) {
  38. super.init(frame: frame)
  39. addBadgeToButon(badge: nil)
  40. }
  41. func addBadgeToButon(badge: String?) {
  42. badgeLabel.text = badge
  43. badgeLabel.textColor = badgeTextColor
  44. badgeLabel.backgroundColor = badgeBackgroundColor
  45. badgeLabel.font = badgeFont
  46. badgeLabel.sizeToFit()
  47. badgeLabel.textAlignment = .center
  48. let badgeSize = badgeLabel.frame.size
  49. let height = max(18, Double(badgeSize.height) + 5.0)
  50. let width = max(height, Double(badgeSize.width) + 10.0)
  51. var vertical: Double?, horizontal: Double?
  52. if let badgeInset = self.badgeEdgeInsets {
  53. vertical = Double(badgeInset.top) - Double(badgeInset.bottom)
  54. horizontal = Double(badgeInset.left) - Double(badgeInset.right)
  55. let x = (Double(bounds.size.width) - 10 + horizontal!)
  56. let y = -(Double(badgeSize.height) / 2) - 10 + vertical!
  57. badgeLabel.frame = CGRect(x: x, y: y, width: width, height: height)
  58. } else {
  59. let x = self.frame.width - CGFloat((width / 2.0))
  60. let y = CGFloat(-(height / 2.0))
  61. badgeLabel.frame = CGRect(x: x, y: y, width: CGFloat(width), height: CGFloat(height))
  62. }
  63. badgeLabel.layer.cornerRadius = badgeLabel.frame.height/2
  64. badgeLabel.layer.masksToBounds = true
  65. addSubview(badgeLabel)
  66. badgeLabel.isHidden = badge != nil ? false : true
  67. }
  68. required init?(coder aDecoder: NSCoder) {
  69. super.init(coder: aDecoder)
  70. self.addBadgeToButon(badge: nil)
  71. fatalError("init(coder:) has not been implemented")
  72. }
  73. }