如何从UITableViewCell显示UIDatePicker
,并让datepicker
在顶部有一个工具栏,让您重新签名?有没有关于如何做到这一点的好教程?
答案 0 :(得分:4)
我最近不得不做同样的事情。
UITextField
插入UITableViewCell
(您可能需要创建自定义UITableViewCell
,具体取决于您是希望它显示在UITableView
的每个动态单元格上还是一个静态单元格。为UIDatePicker
,UIToolbar
和UITextField
创建属性,然后在IB中将UITextField
属性与UITextField
相关联在步骤1中创建(如果您使用的是自定义UITableViewCell
类,那么UITextField
属性需要去的地方):
@property (strong, nonatomic) UIDatePicker * datePicker;
@property (strong, nonatomic) UIToolbar * datePickerToolbar;
@property (strong, nonatomic) IBOutlet UITextField *textField;
...
@synthesize datePicker, datePickerToolbar, textField;
设置您的UIDatePicker
,UIToolbar
和UITextField
:
- (void)viewDidLoad {
// Initialise UIDatePicker
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeTime;
[datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged]; // method to respond to changes in the picker value
// Setup UIToolbar for UIDatePicker
datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
[datePickerToolbar setBarStyle:UIBarStyleBlackTranslucent];
UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissPicker:)]; // method to dismiss the picker when the "Done" button is pressed
[datePickerToolbar setItems:[[NSArray alloc] initWithObjects: extraSpace, doneButton, nil]];
// Note: If you're using dynamic cells, the below 2 lines need to be in your cellForRowAtIndexPath method instead.
// Set UITextfield's inputView as UIDatePicker
textField.inputView = datePicker;
// Set UITextfield's inputAccessoryView as UIToolbar
textField.inputAccessoryView = datePickerToolbar;
}
设置dismissPicker
方法:
-(void)dismissPicker:(id)sender{
[textField resignFirstResponder];
}
设置datePickerValueChanged
方法:
- (void)datePickerValueChanged:(id)sender{
NSDate *selectedDate = datePicker.date;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm"];
[textField setText:[df stringFromDate:selectedDate]];
}
注意:在我的代码中,我需要界面来显示时间,因此在此设置日期格式(HH:mm
)。因此,您还会注意到UIDatePicker
中的viewDidLoad
初始化代码中,我将其模式设置为UIDatePickerModeTime
。对于日期选择,您可能需要将其设置为UIDatePickerModeDate
。
答案 1 :(得分:3)
您可以在UITableViewCell中放置一个不可见的UITextField,并将UITextFields输入视图设置为UIDatePicker。我们这里是代码:
yourdatePicker = [[UIDatePicker alloc]init];
yourtextField.inputView = yourdatePicker;
答案 2 :(得分:0)
我正在使用ActionSheetPicker [1]。它允许您从与当前场景部分重叠的动作表中显示任何类型的选取器。此外,您可以在视图顶部添加按钮(如取消或“今天”)和标题。
[1]:Tim Cinel的原始版本:https://github.com/TimCinel/ActionSheetPicker Hari Karam Singh的改进:https://github.com/Club15CC/ActionSheetPicker 修正了我的分支中的弃用(我认为它现在已经扩散到其他分支中):https://github.com/booiiing/ActionSheetPicker