Shake-to-undo
将此行放入您的 appDelegate 的application:didFinishLaunchingWithOptions:
方法中:
application.applicationSupportsShakeToEdit = YES;
并在相关的 viewController.m
-(BOOL)canBecomeFirstResponder {
return YES;
}
此代码的其余部分位于 viewController.m
属性
把它放在类扩展中......
@interface myViewController()
@property (weak, nonatomic) IBOutlet UITextField *inputTextField;
@end
将其链接到 Interface Builder 中的文本字段。
Undo 方法
将自身的调用添加到重做堆栈
- (void)undoTextFieldEdit: (NSString*)string
{
[self.undoManager registerUndoWithTarget:self
selector:@selector(undoTextFieldEdit:)
object:self.inputTextField.text];
self.inputTextField.text = string;
}
(我们不需要创建 NSUndoManager 实例,我们从 UIResponder 超类继承一个)
撤消操作
摇动撤消不需要,但可能有用...
- (IBAction)undo:(id)sender {
[self.undoManager undo];
}
- (IBAction)redo:(id)sender {
[self.undoManager redo];
}
undo 方法的调用
这里有两个不同的例子来改变 textField 的内容……</p>
示例 1
通过按钮操作设置 textField 的内容
- (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 调用在两种方法中是相同的
示例 2
直接键盘输入编辑
#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;
}