在@selector 方法中传递参数

Pass arguments in @selector method

我在 @selector 方法中传递参数时出错。

这是我的代码:

-(void) accessoryView : (UITextField*) textField
{

    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.barStyle = UIBarStyleBlackTranslucent;
    numberToolbar.items = @[[[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad )],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:@"Apply" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:textField:)]];


    [numberToolbar sizeToFit];
    textField.inputAccessoryView = numberToolbar;
}

-(void)doneWithNumberPad : (UITextField*) txt : (id) sender {

}

第一:你的选择器是错误的。我应该 action:@selector(doneWithNumberPad::) 或将您的第二个方法重命名为 -(void)doneWithNumberPad : (UITextField*) txt textField: (id) sender.

但是其次:您不能使用操作方法发送自定义的附加参数。您应该通过 属性 访问文本字段。在您的情况下,当文本字段中的编辑开始时,您可以将当前文本字段存储在 属性 中。你的视图控制器应该实现 UITextFieldDelegate 来接收这个事件。

您可以为您的文本字段寻求参考变量的帮助。将全局 属性 声明为文本字段。保留当前活动文本字段的引用,并根据您的要求以每种方法访问它。

UITextField *activeTextField;

// UITextField Delegates
-(void)textFieldDidBeginEditing:(UITextField *)textField {     
     activeTextField = textField;
}

您可以在 class 的任何地方使用此 activeTextField 属性。

您需要将 class 定义为 UITextField 的委托。

self.yourTextField.delegate = self