ios 如果用户以编程方式点击 UITextfield,如何显示 UIDatePicker

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21011968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:02:32  来源:igfitidea点击:

How to display UIDatePicker if user hit the UITextfield Programmatically

iosiphoneobjective-cxcode

提问by user2930730

I'd like to Display UIDatePicker only when user the UITextField is Clicked. When the date is picked, it should be shown in the same UITextField.I want to implement UIDatePicker programmatically.I know how to write the code of UITextField Programmatically. I even don't know how to call the UIDatePicker.

我只想在用户单击 UITextField 时显示 UIDatePicker。选择日期时,应该显示在同一个UITextField中。我想以编程方式实现UIDatePicker。我知道如何以编程方式编写UITextField的代码。我什至不知道如何调用 UIDatePicker。

Date of Birth.m

出生日期.m

UITextField txtDOB=[[UITextField alloc]initWithFrame:CGRectMake(10, 190, 300, 20)];

txtDOB.borderStyle=UITextBorderStyleNone;

txtDOB.backgroundColor=[UIColor clearColor];

[txtDOB setUserInteractionEnabled:NO];

txtDOB.font=[UIFont systemFontOfSize:14.0];

txtDOB.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;

txtDOB.textAlignment=NSTextAlignmentLeft;

txtDOB.delegate=self;

[self.view addSubview:txtDOB];

回答by Fabio Berger

The easiest way is to implement the datePickeris as following:

最简单的方法是实现datePicker如下:

Create the datePicker:

创建 datePicker:

self.datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero];
[self.datePicker setDatePickerMode:UIDatePickerModeDate];
[self.datePicker addTarget:self action:@selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];

Then link the datePickerto the textfieldinputView:

然后链接datePickertextfieldinputView:

self.textField.inputView = self.pickerView;

In the end you can catch the action when a date was picked, and convert the date to a string, to show the selected date in the textField

最后,您可以捕捉选择日期时的动作,并将日期转换为字符串,以在 textField

- (void)onDatePickerValueChanged:(UIDatePicker *)datePicker
{
    self.textField.text = [self.dateFormatter stringFromDate:datePicker.date];
}

回答by iDeveloper

    UIDatePicker *picker1   = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 210, 320, 216)];
    [picker1 setDatePickerMode:UIDatePickerModeDate];
    picker1.backgroundColor = [UIColor whiteColor];
    [picker1 addTarget:self action:@selector(startDateSelected:) forControlEvents:UIControlEventValueChanged];

//    [picker1 addSubview:toolBar];
    self.birthTxt.inputView  = picker1; // Here birthTxt is Textfield Name replace with your name

回答by Mani

Before going to this code, you need to just know about UIActionSheetand You need to implement UIActionShetDelegateand UITextFieldDelegateIn the textFieldDidBeginEditingyou need to show the action sheet as below:

临睡前这个代码,你只是需要知道UIActionSheet和你需要实现UIActionShetDelegateUITextFieldDelegatetextFieldDidBeginEditing您需要显示的动作片,如下:

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
   UIActionSheet *asheet = [[UIActionSheet alloc] initWithTitle:@"Select Date" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Select", nil];
  [asheet showInView:[self.view superview]];
  [asheet setFrame:CGRectMake(0, 117, 320, 383)];
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
  {
    UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 320, 240)];

   [pickerView setMinuteInterval:5];
   [pickerView setTag: DatePickerTag];

  [actionSheet addSubview:pickerView];
  NSArray *subviews = [actionSheet subviews];

  [[subviews objectAtIndex:SelectButtonIndex] setFrame:CGRectMake(20, 250, 280, 46)];
  [[subviews objectAtIndex:CancelButtonIndex] setFrame:CGRectMake(20, 300, 280, 46)];

}

回答by vky

  • First indicate that your class conforms to the UITextFieldDelegateprotocol

  • Then in viewDidLoadset the delegateand tagof your text field.

     yourTextField.delegate = self;  
     yourTextField.tag = 111;
    
  • Then implement the following delegate method:

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {   
        if (textField.tag==111) {  
            [self showDatePicker];  
        }  
        return YES;  
    }
    
  • Now implement a function showDatePicker

    - (void)showDatePicker {  
        datePicker = [[UIDatePicker alloc] init];
        datePicker.backgroundColor=[UIColor whiteColor];
    
        UIToolbar *toolbar = [[UIToolbar alloc]init];
        [toolbar sizeToFit];
    
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(showSelectedDate)];    
    
        doneBtn.tintColor = [UIColor whiteColor];  
    
        UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];    
    
        toolbar.backgroundColor = [UIColor colorWithRed:5.0/255.0 green:110.0/255.0 blue:170.0/255.0 alpha:1];  
    
        [toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft,doneBtn ,nil]];  
    
        [yourTextField setInputAccessoryView:toolBar];  
    
        yourTextField.inputView = datePicker;   
    }
    
  • 首先表明你的类符合UITextFieldDelegate协议

  • 然后在viewDidLoad设置文本字段的delegatetag

     yourTextField.delegate = self;  
     yourTextField.tag = 111;
    
  • 然后实现以下委托方法:

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {   
        if (textField.tag==111) {  
            [self showDatePicker];  
        }  
        return YES;  
    }
    
  • 现在实现一个功能 showDatePicker

    - (void)showDatePicker {  
        datePicker = [[UIDatePicker alloc] init];
        datePicker.backgroundColor=[UIColor whiteColor];
    
        UIToolbar *toolbar = [[UIToolbar alloc]init];
        [toolbar sizeToFit];
    
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(showSelectedDate)];    
    
        doneBtn.tintColor = [UIColor whiteColor];  
    
        UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];    
    
        toolbar.backgroundColor = [UIColor colorWithRed:5.0/255.0 green:110.0/255.0 blue:170.0/255.0 alpha:1];  
    
        [toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft,doneBtn ,nil]];  
    
        [yourTextField setInputAccessoryView:toolBar];  
    
        yourTextField.inputView = datePicker;   
    }
    

OR you can do it simply in your viewDidLoadas follows:

或者您可以简单地viewDidLoad按照以下方式进行操作:

datePicker = [[UIDatePicker alloc] init];
datePicker.backgroundColor = [UIColor whiteColor];  

UIToolbar *toolbar = [[UIToolbar alloc]init]; 

[toolbar sizeToFit];    

 UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self
 action:@selector(showSelectedDate)];    

 doneBtn.tintColor = [UIColor whiteColor];  

 UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
 target:nil action:nil];    

toolbar.backgroundColor = [UIColor colorWithRed:5.0/255.0 green:110.0/255.0 blue:170.0/255.0 alpha:1];  

[toolBar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, doneBtn , nil]];  

[yourTextField setInputAccessoryView:toolbar];  

yourTextField.inputView = datePicker;

回答by Gyanendra Singh

You need to add a proper selector when editing begins on UITexfield, use below code

在 UIExfield 上开始编辑时,您需要添加适当的选择器,请使用以下代码

 [txtDOB addTarget:self action:@selector(textbeginEditing:) forControlEvents:UIControlEventEditingDidBegin];

And then implelemt the textbeginEditing method to open the datepicker.

然后实现 textbeginEditing 方法打开日期选择器。

-(void)textbeginEditing:(id)sender{

UIActionSheet __autoreleasing * date_sheet = [[UIActionSheet alloc] initWithTitle:@"Select the date" delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];

date_sheet.tag = 2;

[date_sheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];

datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.hidden = NO;
datePicker.date = [NSDate date];

// Implement the method labelChange
 [datePicker addTarget:self
                action:@selector(labelChange:)
      forControlEvents:UIControlEventValueChanged];


[date_sheet addSubview:datePicker];

UISegmentedControl __autoreleasing *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];

closeButton.momentary = YES;    
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);    
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;    
closeButton.tintColor = [UIColor blackColor];

[closeButton addTarget:self action:@selector(dissmissDatePicker:) forControlEvents:UIControlEventValueChanged];

[date_sheet addSubview:closeButton];
[date_sheet showInView:[[UIApplication sharedApplication] keyWindow]];    
[date_sheet setBounds:CGRectMake(0, 0, 320, 400)];
}

labelChange method implementation

labelChange 方法实现

-(void)labelChange:(UIDatePicker *)sender{
NSDateFormatter __autoreleasing *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
 dateFormat.dateStyle = NSDateFormatterMediumStyle;
 NSString *dateString =  [dateFormat stringFromDate:sender.date];
 txtDOB.text = dateString; 
}

回答by chandru

This will be simple, try this
When U click the textField, this method is called.

这会很简单,试试这个
当你点击 textField 时,这个方法被调用。

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

Then, we dont want to display the keyboard.

然后,我们不想显示键盘。

[textField resignFirstResponder];  

Then, to display the datePicker

然后,显示日期选择器

datePicker=[[UIDatePicker alloc]init];
[datePicker setFrame:CGRectMake(<ur dimension>)];
datePicker.datePickerMode=UIDatePickerModeDateAndTime;
datePicker.timeZone = [NSTimeZone localTimeZone];
[datePicker addTarget:self action:@selector(done) forControlEvents:UIControlEventValueChanged];  

This will display the datePicker.
Then U want to display the selected value in textField

这将显示日期选择器。
然后你想在 textField 中显示选定的值

-(void)done
{
  NSString *dateStri=[dateFormater stringFromDate:datePicker.date];
    [timingTextField setText:[NSString stringWithFormat:@"%@",dateStri]];
}  

Try this, and update me the result

试试这个,然后更新我的结果

回答by Tapas Pal

First make userIntraction enable

首先使 userIntraction 启用

[txtDOB setUserInteractionEnabled:YES];

[txtDOB setUserInteractionEnabled:YES];

and add your picker view as input view of this text filed

并将您的选择器视图添加为该文本文件的输入视图

[txtDOB setInputView:pickerview]

[txtDOB setInputView:pickerview]