Skip to content

Instantly share code, notes, and snippets.

@T-Pham T-Pham/MyTextField.swift
Last active Aug 15, 2016

What would you like to do?
Custom UIControlEvents

The gist is about how to add a custom UIControlEvents. It demonstrates adding a BackSpaceDidPress event, which is fired whenever users tap the backspace keyboard key, to a custom UITextField class. The view controller then listens for the event and do navigation to the previous text field if users press backspace on an empty text field.

struct MyTextFieldEvents: OptionSetType {
let rawValue: UInt
static let BackSpaceDidPress = MyTextFieldEvents(rawValue: 1 << 24)
class MyTextField: UITextField {
func addTarget(target: AnyObject?, action: Selector, forControlEvents controlEvents: MyTextFieldEvents) {
super.addTarget(target, action: action, forControlEvents: UIControlEvents(rawValue: controlEvents.rawValue))
override func deleteBackward() {
sendActionsForControlEvents(UIControlEvents(rawValue: MyTextFieldEvents.BackSpaceDidPress.rawValue))
class MyViewController: UIViewController {
@IBOutlet var myPreviousTextField: MyTextField!
@IBOutlet var myTextField: MyTextField!
override func viewDidLoad() {
myTextField.addTarget(self, action: #selector(MyViewController.backSpaceDidTap), forControlEvents: .BackSpaceDidPress)
func backSpaceDidTap(textField: MyTextField) {
if textField == myTextField && !textField.hasText() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.