请注意,这是一个设计问题,而不是功能问题。我已经知道如何实现以下内容,我只是想找出设计它的最佳方法。
我有一个 iOS 应用程序,UIViewControllers
整个应用程序中的一些应用程序都有UITextFields
输入UIDatePicker
视图。代码如下:
- (void) viewDidLoad
{
self.dateField.inputView = [self createDatePicker];
}
- (UIView *) createDatePicker
{
UIView *pickerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, TOOLBAR_HEIGHT + KEYBOARD_HEIGHT)];
UIDatePicker *picker = [[UIDatePicker alloc] init];
[picker sizeToFit];
picker.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
picker.datePickerMode = UIDatePickerModeDate;
[picker addTarget:self action:@selector(updateDateField:) forControlEvents:UIControlEventValueChanged];
[pickerView addSubview:picker];
// Create done button
UIToolbar* toolBar = [[UIToolbar alloc] init];
toolBar.barStyle = UIBarStyleBlackTranslucent;
toolBar.translucent = YES;
toolBar.tintColor = nil;
[toolBar sizeToFit];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:self
action:@selector(doneUsingPicker)];
[toolBar setItems:[NSArray arrayWithObjects:flexibleSpace, doneButton, nil]];
[pickerView addSubview:toolBar];
picker.frame = CGRectMake(0, toolBar.frame.size.height, self.view.frame.size.width, pickerView.frame.size.height - TOOLBAR_HEIGHT);
toolBar.frame = CGRectMake(0, 0, self.view.frame.size.width, TOOLBAR_HEIGHT);
return pickerView;
}
- (void) doneUsingPicker
{
[self.dateField resignFirstResponder];
}
- (void) updateDateField: (UIDatePicker *) datePicker
{
self.dateField.text = [self.formatter stringFromDate:datePicker.date];
}
问题是,我一直不得不在整个应用程序中将这段代码粘贴到具有 UITextFields 和 UIDatePicker 输入视图的不同类中。什么是最好的设计方法,以尽量减少重复代码。我曾想过拥有一个UIDatePickerableViewController
包含此代码的超类,但这似乎不可扩展。例如,如果我很快就会有其他类型的输入视图可以附加到文本字段。我应该如何设计这个?