我試圖創建一個應用程序,從api中提取json,並提供一組關於界面的外觀樣式的說明。所以基本上,json將包含一個NSDictionary數組,每個NSDictionary將是一個顯示在屏幕上的對象。以編程方式創建NSObjects ios
在NSDictionary中將顯示如何顯示對象的所有細節,如對象的類型,對象的位置和對象的大小。
我已經編寫代碼來接受一組按鈕到屏幕。
for (int i = 0; i < self.jsonObjects.count; i++) {
NSDictionary *jsonObject = [self.jsonObjects objectAtIndex:i];
if ([[jsonObject objectForKey:@"object"] isEqualToString:@"UIButton"]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSNumber *x = [jsonObject objectForKey:@"xlocation"];
NSNumber *y = [jsonObject objectForKey:@"ylocation"];
NSNumber *width = [jsonObject objectForKey:@"width"];
NSNumber *height = [jsonObject objectForKey:@"height"];
NSString *title = [jsonObject objectForKey:@"title"];
[button setFrame:CGRectMake(x.intValue, y.intValue, width.intValue, height.intValue)];
[button setTitle:title forState:UIControlStateNormal];
[self.view addSubview:button];
}
}
現在我可以爲每個對象提供大量的if語句並讓程序做同樣的事情,但我試圖避免它。
基本上我所要求的是實現這一點的最佳方式是儘量減少編碼並提高代碼的可讀性。
這是我寫的模仿json輸出按鈕的代碼。
NSDictionary *button = [[NSDictionary alloc] initWithObjectsAndKeys:@"UIButton", @"object",@"PressMe",@"title",@"10",@"xlocation",@"10",@"ylocation",@"100",@"width",@"100",@"height", nil];
NSDictionary *button2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"UIButton", @"object",@"Dont Press",@"title",@"10",@"xlocation",@"210",@"ylocation",@"100",@"width",@"100",@"height", nil];
self.jsonObjects = [[NSArray alloc] initWithObjects:button,button2, nil];
由於我仍然必須創建api,所以json輸出可以非常靈活。我正想着有一個數組的數組。其中數組中的每個數組都是一組按鈕或文本字段數組。那麼我只需要大約20-30個數組來覆蓋不同的對象類型,並且可以遍歷主數組,然後遍歷每個按鈕或文本字段的數組。
爲禮Ganem
object UIView * 0x07145c60
UIResponder UIResponder
_layer CALayer * 0x07145e80
_tapInfo id 0x00000000
_gestureInfo id 0x00000000
_gestureRecognizers NSMutableArray * 0x00000000
_subviewCache NSArray * 0x075213e0
_charge float 0
_tag NSInteger 0
_viewDelegate UIViewController * 0x00000000
_backgroundColorSystemColorName NSString * 0x00000000
_viewFlags <anonymous struct>
坦率地說,堅果是開始編碼,並丟棄前3-4次嘗試。你最終會理解這些問題,並以合理的方式解決問題。 – 2013-04-09 12:15:03