UIControl+Extension.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // UIControl+Extension.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. import UIKit
  26. public class ActionClosure {
  27. public let selector: Selector
  28. private let closure: (_ sendersender: Any?) -> Void
  29. init(_ attachObj: AnyObject, closure: @escaping (_ sender: Any?) -> Void) {
  30. self.closure = closure
  31. self.selector = #selector(target(_ :))
  32. objc_setAssociatedObject(attachObj, UUID().uuidString, self, .OBJC_ASSOCIATION_RETAIN)
  33. }
  34. @objc func target(_ sender: Any?) {
  35. closure(sender)
  36. }
  37. }
  38. public extension UIControl {
  39. func action(for event: UIControl.Event, _ closure: @escaping (_ object: Any?) -> Void) {
  40. let actionClosure = ActionClosure(self, closure: closure)
  41. self.addTarget(actionClosure, action: actionClosure.selector, for: event)
  42. }
  43. }