Remove @“” from NSString or typecast NSString into variable name

后端 未结 4 425
星月不相逢
星月不相逢 2021-01-25 08:56

I read a NSString from file and then I want to #define this as a UIColor so I can quickly change color\'s.

I want something to work like so:

#define GRAY         


        
相关标签:
4条回答
  • 2021-01-25 09:22

    When you say 'read from file the string : @"GRAY"' do you mean at application run time? if so, then you cannot use #define(s), which are happening at compile time.

    0 讨论(0)
  • 2021-01-25 09:24

    You could load the colors into a NSDictionary.

    // Put this in some global scope
    NSDictionary *colors = [NSDictionary dictionaryWithObjectsAndKeys: 
        [UIColor darkGrayColor], @"GRAY", nil];
    
    // using the dictionary
    myController.view.backgroundColor = [colors objectForKey:kColor];
    
    0 讨论(0)
  • 2021-01-25 09:44

    You can't do that. Objective-C is a compiled language, so you can't use a NSString as if it were a piece of code. You will need a way to return a proper color from a string/NSString read from a file.

    0 讨论(0)
  • 2021-01-25 09:44

    Daniel's answer is probably the best. Since he hasn't provided any code, this is one implementation:

    -(UIColor*) colorFromString: (NSString*) colorName
    {
        static NSDictionary colors = nil;
        if (colors == nil)
        {
            colors = [NSDictionary dictionaryWithObjectsAndKeys: 
                                       [UIColor darkGreyColor], @"GRAY",
                                       [UIColor blueColor], @"BLUE",
                                       // etc
                                       nil];
            [colors retain];
        }
        return [colors objectForKey: colorName];
    }
    
    0 讨论(0)
提交回复
热议问题