1
我有一個類似於iphone上的鬧鐘應用程序的選擇器視圖(第一個組件= 1-12,第二個組件= 0-60,第三個組件= am/pm)。我所做的是在picker視圖的didSelect委託中。從UIPickerView獲取NSDate
if (component == PICKER_HOURS) {
rowSelected = [self.hour objectAtIndex:row % 12];
self.hourSelected = rowSelected;
}
else if (component == PICKER_MINUTES) {
rowSelected = [self.minutes objectAtIndex:row % 60];
self.minuteSelected = rowSelected;
}
else {
rowSelected = [self.ampm objectAtIndex:row];
self.ampmSelected = rowSelected;
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = @"h:mm a";
NSString *timeString = [NSString stringWithFormat:@"%@:%@ %@", _hourSelected, _minuteSelected, _ampmSelected];
NSString *trimmedTimeString = [timeString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSDate *dateSelected = [dateFormatter dateFromString:timeString];
NSDate *dateForAlarm = [self alarmDateForDate:dateSelected];
------
- (NSDate *)alarmDateForDate:(NSDate *)dateSelected {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:[NSDate date]]; // set the date to the current date
NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:dateSelected]; // set the time to what's in the picker
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setYear:[dateComponents year]];
[dateComps setMonth:[dateComponents month]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
NSDate *dateForAlarm = [calendar dateFromComponents:dateComps];
return dateForAlarm;
}
這是正確的做法嗎?我意識到我在選取器視圖中的dateFromString總是在1970年代。所以我不確定這是否是從標準視圖中獲取時間的「標準」方式,以便在將來設置通知。謝謝!