Xcode from scratch for scaredy cats: A slight return (if ... else)


In this post we return to the app that we built last time. The reason for this is that once we've pressed the button it doesn't do anything else, which is rather dull.

In this post we'll change this, so that when we push the button again the background returns to white. The user then gets some feedback and recognition of subsequent button pushes.

We'll be using the "if ... else" statement, which will be familiar to those of you who have experimented or worked with Javascript or PHP among other languages. If it isn't then don't worry as promised in the previous post we'll move slowly and simply.

In order to insert the code we need to open our file called "PushButtonViewController.m" and scroll to the bottom of the file to our piece of code ("method") from last time:

- (IBAction)sender:(id)sender {
self.view.backgroundColor = [UIColor blueColor];
}


and this needs to be entirely replaced by this code:

- (IBAction)sender:(id)sender {

if ([self.view.backgroundColor isEqual:[UIColor blueColor]]) {
self.view.backgroundColor = [UIColor whiteColor];
}
else {
self.view.backgroundColor = [UIColor blueColor];
}

}



The line of code:

self.view.backgroundColor = [UIColor blueColor];

is no different from that which we've become acquainted with in the previous two posts. The things that are added are the "if" and "else" statements, and the line of code that follows the "if", which we'll look at now:

([self.view.backgroundColor isEqual:[UIColor blueColor]])

It is contained within parentheses because these always follow an "if (statement)", it is part of the general syntax. But let's look at what's inside the parentheses:

[self.view.backgroundColor isEqual:[UIColor blueColor]]

We know that self.view.backgroundColor refers to the background colour because, as already stated, we've played around with this in previous posts. We also know that [UIColor blueColor] sets the colour.

The new thing "isEqual:" is a way of "Identifying and Comparing Objects".

Using the square brackets around the whole statement means we are asking the current view a question about its "backgroundColor" property, i.e. is it equal to [UIColor blueColor], or in plain English "background are you blue?" It will reply to this question with a YES or a NO (this is known as a BOOL or Boolean value).

If yes then the "if (statement)" will perform the action within its curly braces and ignore the "else" entirely, but if the "if (statement)" receives a NO then the app will ignore it and default to whatever action is contained within the curly braces of the "else".

Mess around with the code and make some changes to see what happens. Try inserting an "else if (statement)" or two to achieve a cycle of colours as you press the button if you can.

Comments