无法从UIDatePicker中获取日期,该日期在TextField点击打开的UIActionSheet中使用

时间:2014-08-20 10:54:32

标签: ios datepicker uiactionsheet

调用acton表的方法

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [txtSourceTime resignFirstResponder];

    UIActionSheet *sheet1 = [[UIActionSheet alloc] initWithTitle:@"Select Source time" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"Cancel" otherButtonTitles:@"Done", nil];
    [sheet1 setActionSheetStyle:UIActionSheetStyleDefault];
    [sheet1 setTag:3];
    [sheet1 showInView:self.view];

    time = [[UIDatePicker alloc] init];
    time.datePickerMode = UIDatePickerModeDateAndTime;
    time.timeZone = [NSTimeZone localTimeZone];

    [time setBounds:CGRectMake(0, -125, 320, 200)];
    [sheet1 addSubview:time];
    [sheet1 showFromRect:CGRectMake(0, 300, 320, 300) inView:self.view animated:YES];
    [sheet1 setBounds:CGRectMake(0, 0, 320, 500)];
}

单击“操作表”中的“完成”

时,无法在文本框中获取日期

2 个答案:

答案 0 :(得分:1)

需要添加UIActionSheetDelegate方法以了解何时点击完成按钮,然后使用UITextField中的日期更新UIDatePicker。 E.g:

在.h:

添加UIActionSheetDelegate协议:

@interface MyClass : UIViewController <UIActionSheetDelegate, UITextFieldDelegate>
    // ...
@end

在.m:

添加UIActionSheet委托方法以了解何时解除行动表(即点击其中一个按钮):

-(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{

    // buttonIndex of 1 is the Done button
    if (buttonIndex == 1) {
        NSDate *date = time.date;

        // Date shows in text field, but is not nicely formatted
        textField.text = date.description;
    }
}

并设置UIActionSheet的代理:

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

    UIActionSheet *sheet1 = [[UIActionSheet alloc] initWithTitle:@"Select Source time" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"Cancel" otherButtonTitles:@"Done", nil];
    sheet1.delegate = self;

    //...
}

请注意,根据Apple的文档,这不是UIActionSheet的推荐用法:

  

UIActionSheet不是设计为子类,也不应该添加   查看其层次结构。

另一种方法是在UIDatePicker上添加inputView作为UITextField。对于“取消”和“完成”按钮,请在inputAccessoryView上添加UITextField(这将显示在UIDatePicker的顶部。

答案 1 :(得分:0)

添加以下代码.....

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        printf("\n cancel");

    }else{
      printf("\n Done");
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm"];
        NSString *strDate = [dateFormatter stringFromDate:time.date];
        _txtSourceTime.text = strDate;

    }
}