UIControl+Extensions.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // UIControl+Extensions.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 16/08/21.
  6. // Copyright © 2021 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. // Found in Internet
  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. public class ActionClosure {
  26. public let selector : Selector
  27. private let closure : (_ sendersender: Any?) -> ()
  28. init(_ attachObj: AnyObject, closure: @escaping (_ sender: Any?) -> ()) {
  29. self.closure = closure
  30. self.selector = #selector(target(_ :))
  31. objc_setAssociatedObject(attachObj, UUID().uuidString, self, .OBJC_ASSOCIATION_RETAIN)
  32. }
  33. @objc func target(_ sender: Any?) {
  34. closure(sender)
  35. }
  36. }
  37. public extension UIControl {
  38. func action(for event: UIControl.Event, _ closure : @escaping (_ object: Any?) -> Void) {
  39. let actionClosure = ActionClosure(self, closure: closure)
  40. self.addTarget(actionClosure, action: actionClosure.selector, for: event)
  41. }
  42. }