2014-02-24 32 views
0

我創建了一個iOS應用程序,我需要根據API調用的結果顯示不同的視圖。在momment我查詢數據庫,並保存結果,然後使用這個結果,形成一個IF語句,我加載像這樣使用IF語句顯示視圖

CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
JHView *myView = [[JHFewCloudsView alloc] initWithFrame:rect]; 
[self.view myView]; 

正確的觀點。雖然這部作品似乎慢,想了很多代碼爲一個簡單的任務。有沒有更好的方法來擁有多個視圖?你可以在一個視圖中使用很多- (void)drawRect:(CGRect)rect,只需撥打你需要的相關號碼即可。

if ([icon isEqual: @"01d"]) 
    { 
     CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
     JHSunView *sunView = [[JHSunView alloc] initWithFrame:rect]; 
     [self.view addSubview:sunView]; 

    } else if ([icon isEqualToString:@"02d"]) 
    { 
     CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
     JHFewCloudsView *fewCloudsView = [[JHFewCloudsView alloc] initWithFrame:rect]; 
     [self.view addSubview:fewCloudsView]; 
    } 

我現在這樣做的方式意味着我最終會得到15個不同的視圖和非常混亂的代碼。

+0

「'[self.view myView];'」對我來說看起來不正確。 「'self.view = myView'」可能是你的意思? –

+0

顯示「if」代碼。您可能想要使用查找表。但是你的實際問題目前還不是100%清晰的... – Wain

+0

查看更新@Wain和nope [self.view myView]是正確的 – joshuahornby10

回答

0

如果您的代碼與問題中顯示的重複性相同(唯一的區別是類名),那麼您可以創建一個字典,其中的鍵是if語句中的字符串,並且值是類的名稱(作爲字符串)。那麼你的代碼變成:

Class viewClass = NSClassFromString([self.viewConfig objectForKey:icon]); 
CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
UIView *newView = [[[viewClass alloc] initWithFrame:rect]; 
[self.view addSubview: newView]; 
0

在Objective-C,每個班由對象(Class類型),你可以把就像其他對象表示。特別是,您可以使用Class作爲字典中的值,將其存儲在變量中併發送消息。因此:

static NSDictionary *viewClassForIconName(NSString *iconName) { 
    static dispatch_once_t once; 
    static NSDictionary *dictionary; 
    dispatch_once(&once, ^{ 
     dictionary = @{ 
      @"01d": [JHSunView class], 
      @"02d": [JHFewCloudsView class], 
      // etc. 
     }; 
    }); 
    return dictionary; 
} 

- (void)setViewForIconName:(NSString *)iconName { 
    Class viewClass = viewClassForIconName(iconName); 
    if (viewClass == nil) { 
     // unknown icon name 
     // handle error here 
    } 
    CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
    UIView *view = [[viewClass alloc] initWithFrame:rect]; 
    [self.view addSubview:view]; 
}