Simon
Simon

Reputation: 312

Very basic use of self.view.backgroundcolor

I have the array:

self.colors = @[@"redColor",
                    @"blueColor",
                    ];

And then the function:

self.view.backgroundColor = [UIColor [[self.colors[1] ] ];

When I put:

self.view.backgroundColor = [UIColor redColor];

It works immediately. This isn't working 'expected identifier' Can't I use a variable inside the backgroundcolor method?

Upvotes: 1

Views: 260

Answers (3)

Popeye
Popeye

Reputation: 12093

I think you have misunderstood what is returned from self.colors[1] There are a couple of ways that you can do this I will start with the code you already have.

So we have:

// Our array of colors as strings
self.colors = @[@"redColor", @"blueColor", etc];

// Because our colors are strings we need to use NSSelectorFromString to convert 
// the string to a selector
SEL colorSelector = NSSelectorFromString(self.colors[1]);
// Then we need to check if colorSelector actually responds to UIColor
if([UIColor respondsToSelector:colorSelector]) {
    // If the if statement is true then we are good to set the color with it
    self.view.backgroundColor = [UIColor performSelector:colorSelector];
}

Or as others have already said and which would probably be better you could do

self.colors = @[[UIColor redColor], [UIColor blueColor]];

self.view.backgroundColor = self.colors[1];

Upvotes: 0

Yarneo
Yarneo

Reputation: 3002

redColor and blueColor are methods from within the UIColor class, that return a UIColor*.

There are no methods for the class UIColor that receive a string representing a color, and return a UIColor*.

If you want it to work the way you described, form an array of UIColors and not Strings:

self.colors = @[[UIColor redColor],
                [UIColor blueColor]
                ];

Upvotes: 0

sha
sha

Reputation: 17860

You are storing strings in your array. If you want to store color objects change the code to the following:

self.colors = @[[UIColor redColor],
    [UIColor blueColor],
];

And then you can do

self.view.backgroundColor = self.colors[1];

Upvotes: 1

Related Questions