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.
Last active
August 15, 2016 11:05
-
-
Save T-Pham/312697e74e30f641bce183fb8ae4791a to your computer and use it in GitHub Desktop.
Custom UIControlEvents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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