我正在使用SwiftForms为我的表单创建UIPickerView。在SwiftForms示例中完成此操作的方式如下:
row = FormRowDescriptor(tag: "thingsTag", rowType: .Picker, title: "Things")
row.configuration[FormRowDescriptor.Configuration.Options] = [1, 2, 3]
row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in
switch( value ) {
case 1:
return "Thing 1"
case 2:
return "Thing 2"
case 3:
return "Thing 3"
default:
return nil
}
} as TitleFormatterClosure
section1.addRow(row)
显然,这条路线要求你有一组预定的东西"从中选择。但是,我有一个动态数组,对于每个用户都是不同的,这取决于他们在应用程序中做出的先前选择。 (有时候选择器会有3个选择,有时它会有5个,9个等等)
如果没有switch语句,如何让row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure
部分正常工作?我知道for循环会更适合这个但我无法弄清楚如何让它工作而不会抛出错误。
答案 0 :(得分:0)
如果你有数组中选择器视图的标题,为什么不使用下标语法从数组中获取标题,使用值var?
假设您已定义以下数组,并使用以下值进行初始化。
let possibleOptions = ["Doctor", "Teacher", "Engineer", "Politician"]
(请注意,这是在我的示例中,因为没有什么应该修改它。如果您的选择器视图根据输入的输入添加/删除值,您的数组将必须是var。)
然后,在闭包中,假设您的数组按照您希望它显示的顺序排列,那么您只需在闭包中返回以下内容:
return possibleOptions[value]
但是,请注意,如果您尝试从不存在的数组中下标一个值,那么您的程序将崩溃。假设你所有的一切都是正确的,那么这不应该发生,但是在为选择器视图返回标题时检查它是不会有害的。
最终代码看起来像这样:
row = FormRowDescriptor(tag: "thingsTag", rowType: .Picker, title: "Things")
row.configuration[FormRowDescriptor.Configuration.Options] = [1, 2, 3]
row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in
return possibleOptions[value]
} as TitleFormatterClosure
section1.addRow(row)