4

我只是使用一个简单的

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;
}
4

2 回答 2

4

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;
    }
于 2013-01-12T16:15:13.933 回答
0

您无需执行任何操作,除非您禁用它,否则它会正常工作。例如,请参阅此问题

于 2013-01-12T00:50:36.750 回答