繁体   English   中英

无法从UIActionSheet内部使用的UIDatePicker获取日期,UIActionSheet在TextField单击时打开

[英]Unable to fetch date from UIDatePicker which is used inside of UIActionSheet which opens on TextField click

调用acton表的My Method

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

当我在操作表中单击“完成”时,无法在文本框中获取日期

需要添加UIActionSheetDelegate方法来了解何时单击“完成”按钮,然后使用UIDatePicker的日期更新UITextField 例如:

在.h中:

添加UIActionSheetDelegate协议:

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

在他们中:

添加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 对于“取消”和“完成”按钮,在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;

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM