BadgeButton.swift 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // BadgeButton.swift
  3. // Mastodon
  4. //
  5. // Created by Cirno MainasuK on 2021-9-16.
  6. //
  7. import UIKit
  8. import MastodonAsset
  9. import MastodonLocalization
  10. final class BadgeButton: UIButton {
  11. override init(frame: CGRect) {
  12. super.init(frame: frame)
  13. _init()
  14. }
  15. required init?(coder: NSCoder) {
  16. super.init(coder: coder)
  17. _init()
  18. }
  19. }
  20. extension BadgeButton {
  21. private func _init() {
  22. titleLabel?.font = UIFontMetrics(forTextStyle: .caption1).scaledFont(for: .systemFont(ofSize: 13, weight: .medium))
  23. contentEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6)
  24. setAppearance()
  25. }
  26. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  27. super.traitCollectionDidChange(previousTraitCollection)
  28. setAppearance()
  29. }
  30. override func layoutSubviews() {
  31. super.layoutSubviews()
  32. layer.masksToBounds = true
  33. layer.cornerRadius = frame.height * 0.5
  34. }
  35. private func setAppearance() {
  36. setBackgroundColor(Asset.Colors.Label.primary.color, for: .normal)
  37. setTitleColor(Asset.Colors.Label.primaryReverse.color, for: .normal)
  38. tintColor = Asset.Colors.Label.primary.color
  39. }
  40. func setBadge(number: Int) {
  41. let number = min(99, max(0, number))
  42. setTitle("\(number)", for: .normal)
  43. self.isHidden = number == 0
  44. accessibilityLabel = L10n.A11y.Plural.Count.Unread.notification(number)
  45. }
  46. }