@Luda's answer is a great answer,但当我需要将它用于多个文本字段时,我遇到了困难,因此我将其编辑为以下内容:
首先,我为每个textField获取IBOutlets,例如:textField1,textField2
然后我将代码编辑为
- (void)viewDidLoad
{
[super viewDidLoad];
UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
numberToolbar.barStyle = UIBarStyleBlackTranslucent;
numberToolbar.items = [NSArray arrayWithObjects:
[[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(sendToServer:)],
nil];
[numberToolbar sizeToFit];
textField1.inputAccessoryView = numberToolbar;
textField2.inputAccessoryView = numberToolbar;
}
-(void)cancelNumberPad:(UITextField *)textField
{
//here I use if/else to determine which textField was tapped
if(textField == self.textField1)
{
//do some stuff
}else //...
}
-(void) sendToServer:(UITextField *)textField
{
//here I use if/else to determine which textField was tapped
if(textField == self.textField1)
{
//do some stuff
}else //...
}
请注意我必须将冒号:
添加到@selector
,例如@selector(sendToServer:)
这样就可以将正确的TextField作为参数传递。
但是
它不起作用。测试失败:if(textField == self.textField1)
。所以有人知道如何做到这一点吗?
问题是:我如何知道正在编辑哪个文本字段?
答案 0 :(得分:0)
检查if (textField == self.textField)
失败的原因是因为默认情况下传递给UIBarButtonItem选择器的参数实际上是UIBarButtonItem本身。您可以通过在selector方法中放置断点并检查textField参数来验证这一点。
一个可能的解决方案是在没有引入任何代码来循环子视图的情况下,将视图控制器声明为UITextFieldDelegate,然后按如下方式修改选择器:
- (void)sendToServer:(UIBarButtonItem*)barButtonItem {
[self.view endEditing:NO];
}
然后实现委托方法textFieldShouldEndEditing:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
// here you would determine which text field the UIBarButtonItem was associated with
if(textField == self.textField1)
{
// your code here
// and then, if you wanted to dismiss the keyboard
return YES;
} else {
return NO;
}
}
答案 1 :(得分:0)
尝试使用标签 像这样:
textFiled1.tag = 1;
textFiled2.tag = 2;
//当您的文本字段开始编辑时,将调用此方法。
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"tag ==%d",textField.tag);
if(textField.tag == 1){
//do sth
}
}
顺便说一下,你应该在你的XX.h文件中声明UITextFieldDelegate