Skip to content

Super lightweight library (83 lines) to assign closure-based actions to UIControls and the like.

License

Notifications You must be signed in to change notification settings

daaavid/SwiftHandlerKit

Repository files navigation

SwiftHandlerKit

Super lightweight library to assign taggable, closure-based actions to UIControls.

CI Status Version License Platform

Usage

Just use the fuction .on, followed by the event on any UIControl to assign an action for that event.

textField.on(.editingChanged) { textField in
  // no need to cast as UITextField
  print("editingChanged", textField.text!)
}
button.on(.touchUpInside, .touchUpOutside) { button in
  //multiple events
  UIView.animate(withDuration: 0.15) {
    button.transform = .identity
  }
}

The .on function returns an EventHandler object that contains your action. You can add a tag to this EventHandler to identify it.

let touchUpEventHandler = button.on(.touchUpInside, .touchUpOutside) { button in
  print(button)
}

touchUpEventHandler.tag = "buttonTouchUp"

// if you want, you could also do something like this

button.on(.touchDown) { button in
  print(button)
}.tag = "touchDown"

You can find these EventHandlers later by accessing the eventHandlers property (it's a Set) on the ui element you assigned the EventHandler to. You can subcript this set with a tag to find specific event handlers.

if let touchUpEventHandler = button.eventHandlers["buttonTouchUp"] {
  button.eventHandlers.remove(touchUpEventHandler)
}

There's also some support thrown in for UIBarButtonItems. All of the stock UIBarButtonItem inits are now available as closure-based inits.

navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back") { barButtonItem in
  print("leftBarButtonItemWasPressed")
}

You can create UIGestureRecognizers like this as well!

UITapGestureRecognizer { tap in
  print(tap)
}.add(to: view)

Take a peek into SwiftHandlerKit.swift if you want to know more about how it works. It's very short and pretty simple! :^)

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

Installation

SwiftHandlerKit is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'SwiftHandlerKit'

If you get some sort of spec error, try pod repo update or:

pod 'SwiftHandlerKit', :git => 'https://github.com/daaavid/SwiftHandlerKit.git', :branch => 'master'

Author

daaavid, [email protected]

License

SwiftHandlerKit is available under the MIT license. See the LICENSE file for more info.

About

Super lightweight library (83 lines) to assign closure-based actions to UIControls and the like.

Resources

License

Stars

Watchers

Forks

Packages

No packages published