对两个TextField使用相同的UIDatePicker

时间:2012-05-03 10:31:52

标签: ios objective-c xcode uitextfield uidatepicker

我有两个文本域,fromdate和todate.how从同一个datepicker获取不同的日期。我尝试了一些事情,最终在日期更改时在两个文本字段中获得相同的日期。

-(IBAction)dateValueChanged:(id)sender
{
        UIDatePicker *picker = (UIDatePicker *)sender;
        NSDate *dateSelected1 = [picker date];
        NSDate *dateSelected2 = [picker date];

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
        self.fromTextField.text = [dateFormatter stringFromDate:dateSelected1];
       self.toTextField.text = [dateFormatter stringFromDate:dateSelected2];
}

3 个答案:

答案 0 :(得分:7)

在没有UITextFieldDelegatetextFieldDidBeginEditing:

的情况下,可以采用更优雅的方式实施此方法

只需检查firstResponder

即可
- (IBAction)dateValueChanged:(id)sender
{
    NSDate *dateSelected = [picker date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];

    if ([firstTextField isFirstResponder])
    {
      firstTextField.text = [dateFormatter stringFromDate:dateSelected];
    }
    else if ([self.endTextField isFirstResponder])
    {
        secondTextField.text = [dateFormatter stringFromDate:dateSelected];
    }
}

答案 1 :(得分:4)

您可以为TextFields UITextFieldDelegate方法实施textFieldDidBeginEditing:协议,同时为每个TextField设置tag属性,以便轻松识别......

然后当调用textFieldDidBeginEditing:时,您可以读取已开始编辑的文本字段的标记并将其设置为全局值,以便您可以找出日期选择器应更改的文本字段。示例:

- (void)textFieldDidBeginEditing:(UITextField *)textField {

     someGlobalNSInteger = textField.tag; //the current text field tag is now globally set

}

-(IBAction)dateValueChanged:(id)sender {
    UIDatePicker *picker = (UIDatePicker *)sender;
    NSDate *dateSelected1 = [picker date];
    //NSDate *dateSelected1 = [picker date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];

    //self.fromTextField.text = [dateFormatter stringFromDate:dateSelected1];
    //self.toTextField.text = [dateFormatter stringFromDate:dateSelected2];

    UITextField *activeTextField = (UITextField*)[self viewWithTag:someGlobalNSInteger]; //gets text field what is currently being edited
    [activeTextField setText:[dateFormatter stringFromDate:dateSelected1]];

}

但是,如果您不允许文本字段可编辑(因此无法启动键盘),您可能需要一些其他方法来确定textField应该获取更新日期,但我会将其留给你。

希望有所帮助

答案 2 :(得分:1)

实现此目的的最佳方法是使用UITextField中提供的inputview属性。使用Outlet或编程& amp;来初始化您的日期选择器在textfield的委托方法“textFieldDidBeginEditing:”中将其指定为inputView。对于分配日期,您可以在将inputview实际分配给文本字段之前使用自己的业务逻辑。