2017-10-13 51 views
0

我想開發一個動態表單輸入,它可能只是一個UITextField或UIDatePicker。表單輸入應該使用類型(枚舉)進行初始化,因此根據初始化的類型返回String或Date。也許以後我會想添加更多具體的類型返回其他的東西。帶動態返回類型的表單輸入

什麼是最好的做法與Swift 4做到這一點,你會在哪裏存儲數據(如名字,姓氏,出生日期)?在控制器中?泛型類型是否可能的解決方案?

Cheerio

編輯10月18日

感謝用戶帕勒支持!最終的解決方案將某種看起來是這樣:

FormItem.swift

// enum with types for inputs 
enum FormItemType: Int { 
    case text = 0 
    case date = 1 
} 

// enum with types of values 
enum FormInputValue { 
    case text(String) 
    case date(Date) 
} 

// FormItem holds value, label and input 
class FormItem: UIView { 
    var value: FormInputValue? 
    var label: FormLabel? 
    var input: FormInput? 
} 

FormInput.swift

// Protocol to delegate the change to the controller 
protocol FormInputDelegate: NSObjectProtocol { 
    func inputDidChange(value: FormInputValue) 
} 

// FormInput holds the actual input 
class FormInput: UIView { 

    var formInput: FormInput? 
    var delegate: FormInputDelegate? 

    // Init FormInput with type and optional value 
    convenience init(type: FormItemType, value: FormInputValue?) { 
    switch type { 
     case .text(let text)?: 
     self.initTextInput(label: label, value: text) 
     break 
     case .date(let date)?: 
     self.initDateInput(label: label, value: date) 
     break 
     case .none: 
     break; 
    } 
    } 

    // Init specific String input field 
    fileprivate func initTextInput (label: String, value: String?) { 
    formInput = FormTextInput(label: label, value: value) 
    self.addSubview(formInput!) 
    } 

    // Init specific Date input field 
    fileprivate func initDateInput (label: String, value: Date?) { 
    formInput = FormDateInput(label: label, value: value) 
    self.addSubview(formInput!) 
    } 
} 

FormTextInput.swift

// Init actual input with label and optional value 
convenience init(label: String, value: String?) { 
    [...] 
} 

CreateViewController.swift

// Create View Controller where FormInputs 
class CreateViewController: UIViewController { 

    var firstname: String = "Test 123" 

    // Init view controller and add FormItem 
    convenience init() { 
    let fistnameFormItem = FormItem(type: .text, label: NSLocalizedString("Input.Label.Firstname", comment: ""), value: FormInputValue.text(firstname)) 
    } 
} 

回答

0

我會使用單獨的輸入,而不是一個動態輸入。

如果你真的想要一個通用輸入,你可以用枚舉與它的價值關聯的值:

enum FormInputResult { 
    case date(Date) 
    case name(firstName: String, lastName: String) 
} 

在模型 - 視圖 - 控制器體系結構,如名字和生日等數據應該存儲在數據模型。控制器應充當模型和視圖之間的中介。

+0

那麼計劃是在視圖控制器中有幾個表單輸入。表單輸入包含一個標籤和一個不同類型的輸入。由於控制者持有該模型,它負責處理來自表單輸入的回報。所以我認爲表單輸入必須返回不同的類型。 –

+0

我會在界面生成器中靜態地做這件事。但當然,你可以用動態的方式做到這一點。 – Palle

+0

我沒有使用接口構建器或故事板,所以我正在做代碼中的所有接口和組件。我添加了一個帶有示例源代碼的編輯,希望有人能告訴我我錯了什麼。 –