【问题标题】:Using an IF statement to displays views使用 IF 语句显示视图
【发布时间】:2014-02-24 21:42:18
【问题描述】:

我正在创建一个 iOS 应用程序,我需要根据 API 调用的结果显示不同的视图。目前我正在查询数据库,保存结果,然后使用该结果形成一个 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 个不同的视图和非常混乱的代码。

【问题讨论】:

  • "[self.view myView];" 对我来说看起来不正确。 “self.view = myView”大概是你的意思吧?
  • 显示if 代码。您可能想要使用查找表。但是您的实际问题目前还不是 100% 清楚......
  • 查看更新@Wain 并没有 [self.view myView] 是正确的

标签: ios objective-c drawrect


【解决方案1】:

如果您的代码如问题所示重复(唯一的区别是类名),那么您可以创建一个字典,其中键是 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];

【讨论】:

    【解决方案2】:

    在 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];
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 2021-04-16
      • 2021-03-01
      相关资源
      最近更新 更多