[英]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.