• 10 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 02/09/2019

Create your first action

We've just created a connection between our label our controller code. In this chapter we'll connect our button "ACT NeXT" to the controller code by creating what's called an Action!

There's going to be action!

What's Action?

Similar to an Outlet, an Action is a connection between an element of the interface and the code with an addition of one more parameter - an Event.

Action is a connection between an element of the interface and the CODE associated with an event.

What does it mean exactly?

In context of our Acty app, we expect the user to tap on the 'ACT NeXT' button, so that we can initiate our acting task generation. We'll use most popular and natural tapping (or touching) event for a button called TouchUpInside. It occurs after the user touched (Touch) the button and then let go (Up) while their finger was still within the frame of the button (Inside). 

Enough talking, start doing!

Creating an action is similar to creating an outlet:

  • Switch your Editor to Assistant Editor mode with the storyboard on the left, and controller code on the right

  • Press and hold the ctrl key

  • Grab the button on the interface view and drag it to the code under the label outlet.

When you see "Insert Outlet, Action or Outlet Collection", you can let go. An Action configuration popup will appear:

This time, the popup will suggest creating an outlet offering like before outlet's configuration. Let review the proposed configuration and make some adjustments:

  • Connection: A type of connection we want to create. Choose Action.

  • Object: A connecting object: like previously, our controller - View Controller - this is where we dragged it to.

  • Name: A name we want to give to our action. Since our button is meant to generate a new acting task, let's name it exactly that -  generateActingTask:zorro:.

  • Type: A type of the object we are connecting. For our purpose we will not use it, so you can leave it as Any.

  • Event: A type of event that we will associate with the connection. Like we established earlier, the TouchUpInside is the most popular and natural event associated with a button, which is what's selected by default. Feel free to explore the list of available options.

  • Arguments: Just like type, we will not be using this, not to complicate things, set it to None

And finally, click Connect!

This time Xcode generated a different piece of code:

@IBAction func generateActingTask() {
}

Similarly to the keyword  @IBOutlet, we can figure out what  @IBAction means. This keyword also tells Xcode that what follows can be connected to the Interface Builder (same meaning of IB prefix as for the outlets).

But what exactly follows?

Next concept to learn: functions!

What are functions?

Functions is another core concept of a programming language. 

Function is, in essence, a named block of code. It's dedicated to perform one specific task. 

Let's take an example of a company. Every time a hiring manager is interviewing a potential candidate for a developer position, they need to introduce themselves, provide an overview of a company and state what role they are looking to fill.

The code for this process could look like this:

//presentation info
var managerName = "Jane"
var companyInfo = "CoolCode is a mobile app development agency, our mission is to help small companies leverage technology to grow their businesses"
var developersHiring = 2
var developerRole = "Your role would be to create beautiful iPhone apps for our clients. You would collaborate with designers and clients directly to ensure we are delivering the best product possible. In some cases, you would we required to provide maintenance and support for certain existing applications we previously created."
//speaking to interviewee #1
print("Hi, my name is " + managerName)
print(companyInfo)
print("At the moemnt we are looking to hire \(developersHiring) developers")
print(developerRole)
//speaking to interviewee #2
print("Hi, my name is " + managerName)
print(companyInfo)
print("At the moment we are looking to hire \(developersHiring) developers")
print(developerRole)
//...etc. you get the idea!

You get the idea of code repetition when Jane needs to speak to each interviewee.

How about this instead:

func introByManager(){
//presentation info
var managerName = "Jane"
var companyInfo = "CoolCode is a mobile app development agency, our mission is to help small companies leverage technology to grow their businesses"
var developersHiring = 2
var developerRole = "Your role would be to create beautiful iPhone apps for our clients. You would collaborate with designers and clients directly to ensure we are delivering the best product possible. In some cases, you would we required to provide maintenance and support for certain existing applications we previously created."
//speaking to an interviewee
print("Hi, my name is " + managerName)
print(companyInfo)
print("At the moment we are looking to hire \(developersHiring) developers")
print(developerRole)
}
//speaking to interviewee #1
introByManager();
//speaking to interviewee #2
introByManager();
//oh, much better!

In this simple example, we are replacing 4 lines of code with a single line! The new version is also easier to read and understand the logic.

Next, imagine that we need to change the way Jane composes a phrase. Instead of  print("Hi, my name is " + managerName) 

  • we need her to simply say  print("Hi, I'm " + managerName) 

  • or make it more formal  print("Hello, nice to meet you! My name is " + managerName + " I'm a hiring manager.")

In case of our first example, we would need to change the greeting line as many times as we repeat it o_O

And with an improved approach, by using a function, we only need to change one line:magicien:

Now Jane can present herself as many times as she needs to with just one line of code per interviewee! All we need to do is reuse one function!

Here's a basic anatomy of a function:

//declaring my function
func myUsefulFunction(){
//code to perform a task
}

It consists of following components:

  • Keyword  func

  • Name of the function (compose anything you like, practice creating descriptive names, follow a naming convention!)

  • Round parentheses  ()

  • Opening and closing braces  {}

  • Your special code to perform a useful task ;)  {/*code to perform a task*/}

And each time we need to use it - it's a single line of code:

//calling my function
myUsefulFunction()

That's it!

Where were we with our coding?

What's our function?

You know the drill now ;), try to declare a function for generating an acting task.

// Try to do it on your own!
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// I trust you are not cheating...
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// |
// and...
// |
// |
// |
// |
// |
// |
// |
func generateActingTask() {//This is it!
}

And now compare it to what Xcode generated:

@IBAction func generateActingTask() {
}

Very similar but not exactly o_O.

Not a big deal, Xcode just added the  @IBAction  keyword to indicate that this function can be connected as an action to an interface element (IBAction: Interface Builder Action).

An Action is a connection between an element of the interface and a FUNCTION associated with an event.

Before we move on, let's examine our project to make sure it's in tact.

Preventive troubleshooting

Perhaps you attempted to create an action a couple of times, maybe even experimenting with different names for your action. That's positive!

This, however, may have caused some complications in a relationship between the storyboard and the code. The story board may have collected all your previous attempts and is still looking for those records in the code.

To verify that, go to your storyboard, select the button and right click on it to reveal the connections. There should be only one connection referring to the TouchUpInside event and the connection name must match the function name in your code. 

Use the following image to verify that your project is in tact: 

Example of unintended multiple actions
Example of unintended multiple actions

If you find yourself having multiple connections, just delete all the extras by clicking on a little cross (x) to the left of each connection.

All looks good?

Alright, our action is ready.

How do we know it works?

Let's put it to test! 

Testing with Print

Print should sound familiar, it appeared in our sample code when we learned about functions. Print is a function (print()), mostly used to test other functions.

It allows you to 'print' testing text in a Console.

Console?

Remember main panels of Xcode? It's the one at the bottom - the Debugging area (the right section of it is called Console).

 Let's alter our app function to use print like we did in our earlier example:

@IBAction func generateActingTask() {
print("Yay! Our function works!")
}

According to our function anatomy, calling a function is done by writing its name followed by round parentheses:  print()

What's between parentheses?

Anything that appears between parentheses is called parameters. A function can have any number of parameters. 

Parameter is a variable that is passed to a function to be used in that function's context. 

Whether a function requires any parameters depends on its declaration.

Looking back at our introByManager()  function. We did not declare any parameters. We could improve it even further by moving out all the initial data (managerName etc.) and passing it as parameters. This way our intro function would become even more general (or abstract) and we could reuse it with a different manager or for different company etc.

Ok, that's overwhelming! We are done though :magicien:!

Finally, click Run or cmd + rto launch the app. We can verify the console is still empty just like before.  That's a good news, we don't want our function to be called when we start the application. We want that to happen when the user clicks 'ACT NeXT'. Go ahead - click the button! And here it is, our test text appears in console: 

Great work! Your button is now connected to the code! In the next chapter, we will modify its contents according to our app requirements.

Let's Recap!

Functions:

  • Function is a named block of code

  • A function can be reused multiple times

  • Using functions improves readability and maintenance

  • A keyword  func  is used to indicate it's a function

  • Functions can declare any number of parameters

Actions:

  • Action is a connection between an element of the interface and a function associated with an event

  • Creating an action generates the declaration of a function

  • To create an action connection, you need to:

    • Switch your Editor to Assistant Editor mode

    • Perform a control-drag from the object on the interface to the code

    • Select Action for Connection parameter

    • Compose a Name for the action

    • Set Arguments to None

    • Click on Connect to complete the outlet creation

Et si vous obteniez un diplôme OpenClassrooms ?
  • Formations jusqu’à 100 % financées
  • Date de début flexible
  • Projets professionnalisants
  • Mentorat individuel
Trouvez la formation et le financement faits pour vous
Exemple de certificat de réussite
Exemple de certificat de réussite