无需子类 UITextField 来执行此操作。只需在控制器的 viewDidLoad 中设置它的 inputView,就可以了。当文本字段成为第一响应者时,将显示选择器视图而不是键盘。
您可能希望这样做,以便在选择器值更改时采取一些措施。
就像是:
@interface MyViewController ()
@property (weak, nonatomic) IBOutlet UITextField* dateField;
@end
@implementation MyViewController
- (void) viewDidLoad
{
[super viewDidLoad];
UIDatePicker* picker = [[UIDatePicker alloc] init];
[picker addTarget:self
action:@selector(datePickerValueChanged:)
forControlEvents:UIControlEventValueChanged];
self.dateField.inputView = picker;
}
- (void) datePickerValueChanged:(UIDatePicker*)datePicker
{
NSDateFormatter* aFormatter = [[NSDateFormatter alloc] init];
[aFormatter setDateStyle:NSDateFormatterShortStyle];
[aFormatter setTimeStyle:NSDateFormatterShortStyle];
self.dateField.text = [aFormatter stringFromDate:datePicker.date];
}
@end