2013-02-26 19 views
2

請注意,這是一個設計問題,而不是功能問題。我已經知道如何實現以下內容,我只是想弄清楚設計它的最佳方式。如何使用自定義inputViews設計iOS程序

我有一個iOS應用程序,其中幾個UIViewControllers整個應用程序有UITextFieldsUIDatePicker輸入的意見。造成這種情況的代碼如下:

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

的問題是,我一直在不必粘貼在具有的UIDatePicker inputviews UITextFields不同類別的整個應用程序的代碼。什麼是設計這個最好的方法,以儘量減少重複的代碼。我想過有一個UIDatePickerableViewController超類,它包含這個代碼,但是這看起來不是可擴展的。例如,如果我很快就會有其他類型的輸入視圖可以附加到文本字段。我應該如何設計?

回答

2

您可以重構共同超類中的類之間共享的代碼/方法,並繼承其中只修改需要不同的部分的子類。

或者,如果您從不同的角度來看問題:創建一個自定義InputWiewWithDatePicker類,並將該(自)配置和初始化代碼移動到該類的- init方法中。這樣,您就不必到處粘貼這一切,只有一行將被複制:

customControl = [[InputViewWithDatePicker alloc] init]; 
2

我首先想到的是創建一個包含日期選取器和文本字段的一個新的UIView子類你想要的佈局。這可以用筆尖或代碼完成。任何你想添加這種新視圖的地方,它可以是viewDidLoad中的一行,也可以將UIView繪製到筆尖中,然後將它的類更改爲新的視圖類。

1

將您想要的佈局子類化,然後當您分配它時,它將帶有您定義的所有選項。