具有一个DatePicker的多个文本字段

时间:2014-03-09 02:29:06

标签: ios datepicker

我的应用程序包含10个名为日期x的文本字段,每个文本字段都有一个单独的日期选择器,用于输入日期,使用下面的代码。目前,10个文本字段中的每一个都使用相同的代码,因此所有这些代码基本上都使用date2,date3,date4等重复10次。是否可以只使用一个UIDatePicker为每个文本字段分配单个值,以免有这么多代码?这似乎有些重复...

    - (void)viewDidLoad
    {

    date1.delegate = self;

//Date Picker Toolbar to Select Done or Cancel

        UIToolbar* dateToolbar1 = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        dateToolbar1.barStyle = UIBarStyleBlackTranslucent;
        dateToolbar1.items = [NSArray arrayWithObjects:
                              [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelDatePad1)],
                              [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                              [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithDatePad)],
                              nil];
        [dateToolbar1 sizeToFit];

    date1.inputAccessoryView = dateToolbar1;

    self.datePicker1 = [[UIDatePicker alloc]init];
        [self.datePicker1 addTarget:self action:@selector(dateChanged1) forControlEvents:UIControlEventValueChanged];
        self->date1.inputView = self.datePicker1;

    datePicker1.datePickerMode = UIDatePickerModeDate;

    }

    -(void)cancelDatePad1
    {
        [date1 resignFirstResponder];
        date1.text = @"";
    }

    -(void)doneWithDatePad
    {
        [date1 resignFirstResponder];
        [date2 resignFirstResponder];
        [date3 resignFirstResponder];
        [date4 resignFirstResponder];
        [date5 resignFirstResponder];
        [date6 resignFirstResponder];
        [date7 resignFirstResponder];
        [date8 resignFirstResponder];
        [date9 resignFirstResponder];
        [date10 resignFirstResponder];
    }

    - (void)dateChanged1
    {
        NSDate *date_1 = self.datePicker1.date;
        NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc]init];
        [dateFormat1 setLocale:([[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"])];
        [dateFormat1 setDateStyle:NSDateFormatterMediumStyle];
        [dateFormat1 setDateFormat:@"MM/dd/yyyy"];
        self->date1.text = [dateFormat1 stringFromDate:date_1];

    }

1 个答案:

答案 0 :(得分:0)

将所有日期保存在数组中

- (void)doneWithDatePad:(NSArray *)datesArray
{
   for (NSDate *date in datesArray) {
      [date resignFirstResponder];
   }
}