【发布时间】:2017-10-13 09:40:06
【问题描述】:
我想开发一个动态表单输入,它可能只是一个 UITextField 或 UIDatePicker。表单输入应使用类型(枚举)初始化,因此根据初始化的类型返回字符串或日期。也许以后我会想添加更多返回其他东西的特定类型。
使用 Swift 4 执行此操作的最佳做法是什么?您会将数据存储在哪里(如名字、姓氏、生日)?在控制器中?泛型类型是一种可能的解决方案吗?
欢呼
10 月 18 日编辑
感谢用户 Palle 的支持!最终的解决方案看起来像这样:
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))
}
}
【问题讨论】: