UIDatePickerView工作正常。它显示,我可以滚动日期,但由于某种原因我的selectedOB.text不断出现今天的日期!无论我选择哪个日期,它都显示为今天的日期!
我选择了这个:
NSLog和标签显示为:
以下是代码:
- (IBAction)selectDOB:(id)sender
{
UIActionSheet *selectBirthMY = [[UIActionSheet alloc] initWithTitle:@"Select Date of Birth" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Select", nil];
[selectBirthMY setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
[selectBirthMY showInView:[UIApplication sharedApplication].keyWindow];
[selectBirthMY setFrame:CGRectMake(0, 100, 320, 500)];
}
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 320, 216)];
pickerView.datePickerMode = UIDatePickerModeDate;
[pickerView setMinuteInterval:15];
//Add picker to action sheet
[actionSheet addSubview:pickerView];
//Gets an array af all of the subviews of our actionSheet
NSArray *subviews = [actionSheet subviews];
[[subviews objectAtIndex:1] setFrame:CGRectMake(20, 265, 280, 46)];
[[subviews objectAtIndex:2] setFrame:CGRectMake(20, 317, 280, 46)];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIDatePicker *DOBPicker = [[UIDatePicker alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, YYYY"];
NSDate *pickedDOB = [DOBPicker date];
NSString *DOB = [dateFormatter stringFromDate:pickedDOB];
NSLog (@"This is DOB %@", DOB);
self.selectedDOB.text=DOB;
}
答案 0 :(得分:2)
您正在使用两个不同的UIDatePicker实例。您需要使用相同的datePicker实例来获取所选日期
为datePicker创建一个属性
@property (nonatomic, strong) UIDatePicker *pickerView;
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
if(!self.pickerView){
self.pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 320, 216)];
self.pickerView.datePickerMode = UIDatePickerModeDate;
[self.pickerView setMinuteInterval:15];
//Add picker to action sheet
[actionSheet addSubview:self.pickerView];
}
//Gets an array af all of the subviews of our actionSheet
NSArray *subviews = [actionSheet subviews];
[[subviews objectAtIndex:1] setFrame:CGRectMake(20, 265, 280, 46)];
[[subviews objectAtIndex:2] setFrame:CGRectMake(20, 317, 280, 46)];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, YYYY"];
NSDate *pickedDOB = [self.pickerView date];
NSString *DOB = [dateFormatter stringFromDate:pickedDOB];
NSLog (@"This is DOB %@", DOB);
self.selectedDOB.text=DOB;
}
答案 1 :(得分:1)
这是因为您在此方法中分配了新的UIDatePicker实例
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
所以不要创建新实例。使用已创建的datepicker实例。
希望它对你有所帮助。