3

我需要使用 JSON 创建一个动态表单。我已经解析了 JSON,但我不知道如何动态创建表单。请建议一些代码或教程。

[
    {
        "cssClass": "head"
    },
    {
        "cssClass": "input_text",
        "values": "Text Field",
        "fieldsize": "small",
        "required": "undefined",
        "prevalue": "This is text field",
        "autocaps": "none",
        "fieldesc": "text field description"
    },
    {
        "cssClass": "number",
        "values": "Number ",
        "fieldsize": "small",
        "required": "required",
        "prevalue": "This is Number Field",
        "autocaps": "capitalize",
        "fieldesc": "number field description"
    },
    {
        "cssClass": "email",
        "values": "Email",
        "fieldsize": "small",
        "required": "required",
        "prevalue": "This is email field",
        "autocaps": "none",
        "fieldesc": "email field description"
    },
    {
        "cssClass": "password",
        "values": "Password",
        "fieldsize": "small",
        "required": "required",
        "prevalue": "password",
        "autocaps": "none",
        "fieldesc": "password field description"
    },
    {
        "cssClass": "date",
        "values": "Date",
        "fieldsize": "medium",
        "required": "required",
        "prevalue": "datefield",
        "autocaps": "uppercase",
        "fieldesc": "date field description"
    },
    {
        "cssClass": "time",
        "values": "Time",
        "fieldsize": "small",
        "required": "undefined",
        "prevalue": "time field",
        "autocaps": "uppercase",
        "fieldesc": "time field description"
    }
]
4

1 回答 1

1

首先,您需要将 JSON 解析为字典,然后使用每个字典条目实例化自定义对象:

@interface FormItem : NSObject

@property (nonatomic, retain) NSString * cssClass;
@property (nonatomic, retain) NSString * values;
//etc

+(id)initWithDictionary:(NSDictionary*)dictionary;

@end

@implementation FormItem

+(id)initWithDictionary:(NSDictionary*)dictionary {
    if (self = [super init]) {
        _cssClass = [dictionary valueForKey:@"cssClass"];
        //etc
    }
}

@end

一旦你在 NSArray 中拥有这些对象,例如视图控制器中的 self.formItems,你将使用该列表来绑定你的 tableView。在 cellForRowAtIndexPath: 中,您需要将项目拉出:

FormItem *currentItem = self.formItems[indexPath.row];

此时,您将希望动态创建 UITextField 或您需要的任何其他控件并将它们添加到表格单元格中:

if ([currentItem.values isEqualToString:@"Text Field"] {
    UITextField *text = [[UITextField alloc] init...];
    //setup
    [cell.contentView addSubview:text];
}

您可以将这些东西抽象到您的 FormItem 类中,但这是一种快速的方法。

于 2012-11-20T15:08:37.513 回答