【问题标题】:Create dynamic form using JSON in iOS在 iOS 中使用 JSON 创建动态表单
【发布时间】:2012-11-20 11:14:02
【问题描述】:

我需要使用 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"
    }
]

【问题讨论】:

  • 创建包含所有字段的类文件,然后将所有字段存储在 NSArray 中,并在从 WS 获取数据后传递给表视图并重新加载数据
  • 你能提供一些链接或示例代码吗

标签: objective-c json ios5


【解决方案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 类中,但这是一种快速的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2012-05-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多