Shake-to-undo
Put this line in your appDelegate's application:didFinishLaunchingWithOptions:
method:
application.applicationSupportsShakeToEdit = YES;
и в соответствующем viewController.m
-(BOOL)canBecomeFirstResponder {
return YES;
}
остальная часть этого кода входит в viewController.m
Property
Put this in the class extension...
@interface myViewController()
@property (weak, nonatomic) IBOutlet UITextField *inputTextField;
@end
свяжите его до своего текстового поля в Интерфейсном Строителе.
Undo method
Adds an invocation of itself to the redo stack
- (void)undoTextFieldEdit: (NSString*)string
{
[self.undoManager registerUndoWithTarget:self
selector:@selector(undoTextFieldEdit:)
object:self.inputTextField.text];
self.inputTextField.text = string;
}
(мы не должны создавать случай NSUndoManager, мы наследуем один суперклассу UIResponder),
Undo actions
Not required for shake-to-undo, but could be useful...
- (IBAction)undo:(id)sender {
[self.undoManager undo];
}
- (IBAction)redo:(id)sender {
[self.undoManager redo];
}
Invocations of the undo method
Here are two different examples of changing the textField's contents…
Example 1
Set the textField's contents from a button action
- (IBAction)addLabelText:(UIButton*)sender {
[self.undoManager registerUndoWithTarget:self
selector:@selector(undoTextFieldEdit:)
object:self.inputTextField.text];
self.inputTextField.text = @"text";
}
Рискуя потерей ясности, мы можем сократить это к:
- (IBAction)addLabelText:(UIButton*)sender {
[self undoTextFieldEdit: @"text"];
}
поскольку undoManager просьба - то же самое в обоих методах
Example 2
Direct keyboard input editing
#pragma mark - textField delegate methods
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
[self.undoManager registerUndoWithTarget:self
selector:@selector(undoTextFieldEdit:)
object:textField.text];
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//to dismiss the keyboard
[textField resignFirstResponder];
return YES;
}