2014-02-24 58 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]; 
}