【问题标题】:show Done button on number pad for multiple UITextFields在多个 UITextField 的数字键盘上显示完成按钮
【发布时间】:2014-08-25 19:04:22
【问题描述】:

@Luda's answer is a great answer,但是当我需要将它用于多个文本字段时我被卡住了,所以我将其编辑如下:

首先,我为每个文本字段获取 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)。那么有人知道如何正确执行此操作吗?

问题是:我如何知道正在编辑哪个文本字段?

【问题讨论】:

标签: ios iphone keyboard xcode5 user-input


【解决方案1】:

检查if (textField == self.textField) 失败的原因是默认传递给 UIBarButtonItem 选择器的参数实际上是 UIBarButtonItem 本身。您可以通过在任一选择器方法中放置断点并检查 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;
   }
}

【讨论】:

    【解决方案2】:

    尝试使用标签 像这样:

    textFiled1.tag = 1;
    textFiled2.tag = 2;
    

    //当您的文本字段开始编辑时,将调用此方法。

    - (void)textFieldDidBeginEditing:(UITextField *)textField
    
    {
    
    NSLog(@"tag ==%d",textField.tag);
    if(textField.tag == 1){
       //do sth
      }
    
    }
    

    顺便说一句,你应该在你的 XX.h 文件中声明 UITextFieldDelegate

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多