通过点击UIBarButtonItem显示自定义inputView /键盘

时间:2015-10-28 11:21:50

标签: ios objective-c swift keyboard uiresponder

点击工具栏按钮(UIBarButtonItem)时,我想显示自定义日期选择器键盘。

使用UIResponder inputView显示自定义键盘似乎是正确的选择。不幸的是,UIBarButtonItem不是UIResponder的子类。

如何拥有UIBarButtonItem becomeFirstResponder 并携带inputView来显示这样的键盘?

3 个答案:

答案 0 :(得分:0)

为什么要在用户点击UIBarButtonItem时显示键盘? 假设键盘显示在UIBarButtonItem上,当用户使用键盘输入内容时会发生什么?哪个控件可以从键盘接收按键事件?

答案 1 :(得分:0)

您可以按照另一种方法在按钮单击

上显示datePicker,而不是使用inputView方法

showDatePicker是按下按钮的方法,然后点击

-(void)showDatePicker
    {

    UIDatePicker* picker = [[UIDatePicker alloc] init];
                        picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
                        picker.datePickerMode = UIDatePickerModeDate;

    [picker addTarget:self action:@selector(dueDateChanged:) forControlEvents:UIControlEventValueChanged];
                        CGSize pickerSize = [picker sizeThatFits:CGSizeZero];
                        picker.frame = CGRectMake(0.0, 250, pickerSize.width, 460);
                        picker.backgroundColor = [UIColor blackColor];
                        [self.view addSubview:picker];
    }


-(void) dueDateChanged:(UIDatePicker *)sender {
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

    //self.myLabel.text = [dateFormatter stringFromDate:[dueDatePickerView date]];
    NSLog(@"Picked the date %@", [dateFormatter stringFromDate:[sender date]]);
}

要删除 datePicker ,您可以对查看中的其他按钮点击调用的方法或您的自定义removeFromSuperView <使用toolbar < strong>完成按钮。

答案 2 :(得分:0)

我通过创建UITextField

完成了这项工作
let myPicker = UIPickerView()
lazy var pickerInputField: UITextField = {
  let field = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
  self.view.addsubview(field)
  field.delegate = self
  return field
}()

func barButtonItemTouched(sender: Any) {

  // dismiss the picker if it's showing
  if pickerInputField.isFirstResponder {
    pickerInputField.resignFirstResponder()
  }

  pickerInputField.inputView = myPicker
  pickerInputField.becomeFirstResponder() 
}