UIBarButton+Extension.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // UIBarButton+Extension.swift
  3. // Nextcloud
  4. //
  5. // Created by Henrik Storch on 27.01.22.
  6. // Copyright © 2022 Henrik Storch. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. // Author Henrik Storch <henrik.storch@nextcloud.com>
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import UIKit
  25. private var actionKey: Void?
  26. extension UIBarButtonItem {
  27. // https://stackoverflow.com/a/36983811/9506784
  28. private var _action: () -> Void {
  29. get {
  30. return objc_getAssociatedObject(self, &actionKey) as? () -> Void ?? { }
  31. }
  32. set {
  33. objc_setAssociatedObject(self, &actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  34. }
  35. }
  36. convenience init(title: String?, style: UIBarButtonItem.Style, action: @escaping () -> Void) {
  37. self.init(title: title, style: style, target: nil, action: #selector(pressed))
  38. self.target = self
  39. self._action = action
  40. }
  41. convenience init(image: UIImage?, style: UIBarButtonItem.Style, action: @escaping () -> Void) {
  42. self.init(image: image, style: style, target: nil, action: #selector(pressed))
  43. self.target = self
  44. self._action = action
  45. }
  46. @objc private func pressed(sender: UIBarButtonItem) {
  47. _action()
  48. }
  49. }