UIBarButton+Extension.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 Foundation
  25. import UIKit
  26. private var actionKey: Void?
  27. extension UIBarButtonItem {
  28. // https://stackoverflow.com/a/36983811/9506784
  29. private var _action: () -> Void {
  30. get {
  31. return objc_getAssociatedObject(self, &actionKey) as? () -> Void ?? { }
  32. }
  33. set {
  34. objc_setAssociatedObject(self, &actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  35. }
  36. }
  37. convenience init(title: String?, style: UIBarButtonItem.Style, action: @escaping () -> Void) {
  38. self.init(title: title, style: style, target: nil, action: #selector(pressed))
  39. self.target = self
  40. self._action = action
  41. }
  42. convenience init(image: UIImage?, style: UIBarButtonItem.Style, action: @escaping () -> Void) {
  43. self.init(image: image, style: style, target: nil, action: #selector(pressed))
  44. self.target = self
  45. self._action = action
  46. }
  47. @objc private func pressed(sender: UIBarButtonItem) {
  48. _action()
  49. }
  50. }