简体   繁体   English

iOS - 关闭呈现为inputView的UIDatePicker

[英]iOS - Dismiss UIDatePicker presented as inputView

我的UI中有一个文本字段,当它被选中时会显示一个UIDatePicker而不是默认键盘,如何在用户完成时设置一个按钮来关闭选择器?

我所做的是将我的inputView作为自定义视图,其中包含一个UIDatePicker和一个工具栏,上面有一个“完成”按钮连接到一个方法,该方法调用委托方法告诉拥有UITextField的对象解除“键盘”通过调用resignFirstResponder

Create a UIView (namely customDatePickerView) and in that view ,create datepicker and a done button and a cancel button in the xib. 创建一个UIView(即customDatePickerView)并在该视图中,在xib中创建datepicker和一个完成按钮以及一个取消按钮。 In the textfield delegate: 在textfield委托中:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == textfieldName) {
        [textfieldName resignFirstResponder];
         //show the view
         self.customDatePickerView.hidden = NO;

    }

}//dismisses keyboard

Function on Date Picker Value Changed 更改日期选择器值的功能

- (IBAction)onDatePickerClick:(id)sender {

    NSDateFormatter  *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/YYYY"];
    NSDate *selectedDate = [self.wellRecordDatePicker date];
    NSString *recordDate = [dateFormatter stringFromDate:selectedDate];
    self.yourTextfieldName.text = recordDate;


}

- (IBAction)onDoneBtnClick:(id)sender
{
       self.customDatePickerView.hidden = YES;
}
- (IBAction)onCancelBtnClick:(id)sender
{
       self.customDatePickerView.hidden = YES;
}

Hope this will help you. 希望这会帮助你。

You can solve this by adding this 你可以通过添加它来解决这个问题

[self.view endEditing:YES];

Add this where you want to dismiss date picker like i have added this on tap gesture 将此添加到您要解除日期选择器的位置,就像我已添加此功能一样
On viewDidLoad added a Tapgesture 在viewDidLoad上添加了Tapgesture

 UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; // Declare the Gesture.
    gesRecognizer.delegate = self;
    [self.view addGestureRecognizer:gesRecognizer];

After adding this on viewdidLoad Add this method to detect gesture recognizer 在viewdidLoad上添加此项后添加此方法以检测手势识别器

- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"Tapped");
    [self.view endEditing:YES];
}

I've done a similar thing where I've created a view with a button and the UIDatePicker , then presented that view instead of the UIDatePicker alone. 我做了类似的事情,我用按钮和UIDatePicker创建了一个视图,然后单独呈现该视图而不是UIDatePicker Then the button is just connected to an IBAction that moves the view out. 然后按钮IBAction接到一个IBAction ,将视图移出。

This way, the button moves in with the UIDatePicker view and they look "connected" to the user. 这样,按钮随UIDatePicker视图移动,它们看起来与用户“连接”。 You can even define this UIView in your nib and use addSubview: at runtime. 您甚至可以在您的nib中定义此UIView并在运行时使用addSubview:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM