我只是使用一个简单的
self.customerTextField.text = @"text";
但我希望有撤销支持,如果他们摇动手机,他们可以撤销更改。
我有点不知道如何完成这件事。我找到的所有示例都是针对UITextView
的。
======================== 当前迭代的代码 ======================
-(void)getUniqueItemID {
[self.inventoryLibrarian generateUniqueItemIDwithCompletionBlock:^(NSString *string) {
[self undoTextFieldEdit:string];
//self.customTextField.text = string;
}];
}
- (void)undoTextFieldEdit: (NSString*)string
{
[self.undoManager registerUndoWithTarget:self
selector:@selector(undoTextFieldEdit:)
object:self.customTextField.text];
self.customTextField.text = string;
}
-(BOOL)canBecomeFirstResponder {
return YES;
}
Shake-to-undo
把这一行放到appDelegate的application:didFinishLaunchingWithOptions:
方法中:
application.applicationSupportsShakeToEdit = YES;
和相关的viewController.m
-(BOOL)canBecomeFirstResponder {
return YES;
}
其余代码在viewController.m
中<<p> 属性/strong>把它放到类扩展中…
@interface myViewController()
@property (weak, nonatomic) IBOutlet UITextField *inputTextField;
@end
将其链接到Interface Builder中的文本字段。
<<p> 撤消方法/strong>将自身调用添加到重做堆栈
- (void)undoTextFieldEdit: (NSString*)string
{
[self.undoManager registerUndoWithTarget:self
selector:@selector(undoTextFieldEdit:)
object:self.inputTextField.text];
self.inputTextField.text = string;
}
(我们不需要创建NSUndoManager实例,我们从UIResponder超类继承一个)
<<p> 撤消操作/strong>不需要震动撤销,但可能有用…
- (IBAction)undo:(id)sender {
[self.undoManager undo];
}
- (IBAction)redo:(id)sender {
[self.undoManager redo];
}
撤销方法的调用
下面是更改textField内容的两个不同示例…
设置按钮动作的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;
}
你不需要做任何事情,它只是工作,除非你禁用它。