Skip to content

Instantly share code, notes, and snippets.

@T-Pham
Last active August 15, 2016 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save T-Pham/312697e74e30f641bce183fb8ae4791a to your computer and use it in GitHub Desktop.
Save T-Pham/312697e74e30f641bce183fb8ae4791a to your computer and use it in GitHub Desktop.
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))
super.deleteBackward()
}
}
class MyViewController: UIViewController {
@IBOutlet var myPreviousTextField: MyTextField!
@IBOutlet var myTextField: MyTextField!
override func viewDidLoad() {
super.viewDidLoad()
myTextField.addTarget(self, action: #selector(MyViewController.backSpaceDidTap), forControlEvents: .BackSpaceDidPress)
}
func backSpaceDidTap(textField: MyTextField) {
if textField == myTextField && !textField.hasText() {
myPreviousTextField.becomeFirstResponder()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment