我有一个日期选择器。我想让用户在“Von”文本字段(明天上午9点开始)中选择日期和时间,然后选择直到文本字段“bis”(1.5小时后开始)。
一切正常。但是当我点击“von”文本字段时。我的datepicker dint为自己设定了正确的时间。以下是一些截图: from textfield,until textfield
viewDidLoad中:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];
NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit|NSMonthCalendarUnit| NSWeekdayCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
[nowComponents setWeek: [nowComponents week]];
[nowComponents setDay:[nowComponents day]+1];
[nowComponents setHour:9];
[nowComponents setMinute:0];
[nowComponents setSecond:0];
today = [gregorian dateFromComponents:nowComponents];
NSDate *tomorrowat9am = [gregorian dateFromComponents:nowComponents];
//DatePicker wird erstellt
self.thePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 152, 325, 300)];
self.thePicker.datePickerMode = UIDatePickerModeDateAndTime;
[thePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
//starts from tomorrow at 9 am
NSDate *pickereinstelldate= tomorrowat9am;
[self.thePicker setDate:pickereinstelldate];
//set the right format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
NSString *datum =[dateFormatter stringFromDate:self.thePicker.date];
//set the date at textfield "bis" to 1.5 hours later
NSDate *neuesdatum = [beginningOfWeek dateByAddingTimeInterval:3600*1.5]; NSString *neuesd = [dateFormatter stringFromDate:neuesdatum];
//set the textfield with the new date
tfVon.text=datum;
tfBis.text=neuesd;
[self.view addSubview:thePicker];
self.thePicker.hidden=YES;
tfVon.inputView=thePicker;
tfBis.inputView=thePicker;
}
这是行动:
-(IBAction)dateChanged
{
self.date = [thePicker date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
NSString *datum =[dateFormatter stringFromDate:self.date];
NSDate *neuesdatum = [date dateByAddingTimeInterval:3600*1.5];
NSString *neuesd = [dateFormatter stringFromDate:neuesdatum];
//when i click on "Von" textfield
if (dateBOOL==YES)
{
tfVon.text=datum;
tfBis.text=neuesd;
}
//when i click on "bis" textfield
if (dateBOOL==NO) {
tfBis.text=neuesd;
}
}
这里我将datebool设置为no:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField==tfVon)
{
dateBOOL=YES;
self.thePicker.hidden=NO;
return YES;
}
if (textField==tfBis)
{
dateBOOL=NO;
self.thePicker.hidden=NO;
return YES;
}
}
return YES;
}
答案 0 :(得分:0)
您发布的最后一个方法永远不会到达最后一个返回YES。你还有一个额外的}。
“我的datepicker dint为自己设定了正确的时间。” 您的问题并不完全清楚,但从我收集的内容中,您在选择“bis”文本字段后尝试将日期选择器设置为正确的时间。
[datePicker setDate:neuesdatum animated:NO];
如果您尝试将bis文本字段设置为新日期,则必须再次使用dateformatter并将文本字段设置为该新日期。
以下行(neuesd)给你的价值是多少? NSString * neuesd = [dateFormatter stringFromDate:neuesdatum];