2012-11-20 33 views
2

我需要使用JSON創建動態表單。我已經解析了JSON,但我不知道如何動態創建表單。請建議一些代碼或教程。在iOS中使用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" 
    } 
] 
+0

創建與各界類文件,然後將所有存儲在NSArray中,並傳遞給表視圖,一旦你從WS –

+0

獲取數據u可以給一些這方面的鏈接或代碼示例重新加載數據 – user1190239

回答

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中的對象,如自我。在視圖控制器中的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類中,但這是快速的方法。