我正在构建一个iOS应用程序。我正在使用故事板来构建屏幕,我创建了一个包含名称,日期,分钟和最大字符等字段的表单。
我遇到的问题是无法在按钮点击时实现日期选择器,当用户选择日期,日期选择器隐藏时,想要在标签中显示所选日期。
我用谷歌搜索但找不到一个好的教程或库。 我想在选择器中只显示日期和日期。
答案 0 :(得分:30)
-(IBAction)datePickerBtnAction:(id)sender
{
datePicker =[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0,10, 50)];
datePicker.datePickerMode=UIDatePickerModeDate;
datePicker.hidden=NO;
datePicker.date=[NSDate date];
[datePicker addTarget:self action:@selector(LabelTitle:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
rightBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(save:)];
self.navigationItem.rightBarButtonItem=rightBtn;
}
-(void)LabelTitle:(id)sender
{
NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
dateFormat.dateStyle=NSDateFormatterMediumStyle;
[dateFormat setDateFormat:@"MM/dd/yyyy"];
NSString *str=[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:datePicker.date]];
//assign text to label
label.text=str;
}
-(void)save:(id)sender
{
self.navigationItem.rightBarButtonItem=nil;
[datePicker removeFromSuperview];
}
答案 1 :(得分:5)
试试这个:
- (IBAction)date:(id)sender {
datepicker=[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 300)];
datepicker.datePickerMode = UIDatePickerModeDate;
datepicker.hidden = NO;
datepicker.date = [NSDate date];
[datepicker addTarget:self
action:@selector(LabelChange:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datepicker]; //this can set value of selected date to your label change according to your condition
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"M-d-yyyy"]; // from here u can change format..
_selectedDate.text=[df stringFromDate:datepicker.date];
}
- (void)LabelChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"M-d-yyyy"];
_selectedDate.text = [NSString stringWithFormat:@"%@",
[df stringFromDate:datepicker.date]];
[datepicker removeFromSuperview];
}
答案 2 :(得分:2)
答案 3 :(得分:2)
添加隐藏的文本字段视图并配置日期选择器。
[self.xTextFeild setInputView:_datePicker];
然后 什么时候你想要在代码下面打电话。
[self.xTextFeild becomeFirstResponder];
`