无法从UIDatePicker中获取日期,UIDatePicker是在UIDatePicker中使用的,它在TextFi



我的方法,其中操作表被称为

- (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)];
}

当我在actionsheet中单击done时,无法在文本框中获取日期

需要添加一个UIActionSheetDelegate方法来知道何时按下Done按钮,然后用UIDatePicker的日期更新UITextField。例如:

在。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添加为UITextField上的inputView。对于Cancel和Done按钮,在UITextField上添加inputAccessoryView(它将显示在UIDatePicker的顶部)。

添加以下代码.....

- (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;
    }
}

相关内容

最新更新