iOS Tutorials / Swift Tutorials / Objective-C Tutorials / Basic Course

Basic tutorial on using a button to change label using iOS SDK

iOS Tutorials / Swift Tutorials / Objective-C Tutorials / Basic Course IMG_0601.JPG

Hi there, great you have landed here. If you are a complete newbie to the iOS development but have some previous experience with any other platform, this tutorial should be just perfect for you.

This is a first post out of a few that will direct you on a development path towards some really great, cool apps.

If you have played with the Xcode a bit before, just jump to the “Let me write some code already!!!” section.

As we have to start somewhere, the best will be if you download Xcode right from the Apple AppStore. Xcode is a really fabulous  tool that can be greatly expanded by custom plugins and themes. There are some development tools out there but I would suggest you stay with Xcode at least for now as I wouldn’t like you to give up on all this just because you had a problem to get through to some resources or you were unable to find the right help on stackoverflow or other servers as they mostly referring to Xcode.

Tutorial

In this first tutorial we will learn how to create a button on the screen and how to assign a CTA (call to action) to it which will than increment a number on our label which will lay right above the button.

All files will be always available in a git repository on:
https://github.com/xprogresscom/ios_objc_basic_tutorial

Every step/milestone mentioned in the tutorial will have it’s own release here:
https://github.com/xprogresscom/ios_objc_basic_tutorial/releases

Open your Xcode first and tap on create new project. A window will open, offering you a set of different templates. Obviously Xcode is not only for developing iPhone or iPad apps. Xcode can be used to develop Mac apps as well as all sorts if libraries and frameworks that you could later re-use across your projects.

As we are now focusing on developing an iOS app, please select a single view project iOS application and click next.

On the next screen, type in the name of your project, and if not prefilled your organisation name.

The organisation identifier is one of the most important settings in your app. It will accompany your app for ever and changing it after you publish to the AppStore would be like publishing a brand new app.

Also called a bundle identifier, this string should be a reversed URL for the developed product but I guess this is kinda abstract as you don’t actually need to have any URL (nor you have to own one you have put in to be able to publish to store.

You can for example use cz.mangoweb.supercoolapp or com.joe-biggs.animator-app, doesn’t really matter as long as it hasn’t been registered by anyone else before.

1_create_project
Image 1

For our example app, you can un-tick Core Data as we won’t most definitely be tapping into that Pandora’s box anytime soon!

I would say it is a good practice to leave the unit tests in for the time being as you never know how quickly you might progress on your ultimate development journey and believe you me, you won’t be wanting to have any bigger project without appropriate tests … but hey, we’ll get to that in time!

Click next, select yes on local git repo and select a folder where you would like to have your project. You don’t need to create any subfolders as Xcode 7.x will most definitely create one with all your project files anyway.

Heureka, we have an iOS project

What has appeared in front of you might now look somehow familiar. I bet you have tried to create a couple of projects before you decided that looking for a tutorial might actually be a good idea and also the layout is not that different from other IDE’s like Eclipse or Visual Studio so all seems ok.

On the left you have your project structure. Careful here, please note I have mentioned a project structure, not file structure. This is because file structure in the filesystem don’t necessarily correlate to the groups (that’s how are the yellow folder called) in your project folder. I have witnessed a couple of arguments already between people who believe that the groups and physical folder structure should correspond. I personally believe that it is not necessary to keep the source files in folders, that physically you can leave all files in one folder and I believe anything more would be just a completely pointless exercise.

There are a few pre-created files available to you in the left column. The most important one that we’ll be working with in this tutorial are the ViewController and the Main.storyboard which will contain our visual elements. The .h is a header file where you declare type of the class and what class does it inherit from and in the .m (implementation file) you keep your business logic. There is also an AppDelegate which is extremely important but we won’t be needing any changes to be made to this file today.

On the top you can probably see something that very much looks like a play and stop buttons. These buttons will enable you to run and stop your builds on both, simulators as well as actual devices. The type of the device you can select is further to the right from the play/stop buttons. Just try and take a peek at all the simulators that are available to you. If you have an iPhone or iPad connected, you should be able to see your device on the top of that list too.

In this tutorial I would like to get you into a routine of using some really helpful keyboard shortcuts so try now what happens when you press a combination of Cmd and R. Cmd+R will build your project if there are no issue with it and will automatically launch the previously selected device. There is also Cmd+K which will clean your targets (useful to do when you get some unexplainable bug that you could swear you have fixed just a second ago) and Cmd+B which only builds/compiles your project without launching the app itself.

I very often use the Cmd+B combination instead of saving the files individually as in order to get all the changes built, the compiler needs all the latest changes to be saved so Xcode saves all for you to save time.

Following picture shows the initial screen for your orientation. In the right bar you usually get some preferences for objects that you click on the left or middle section of Xcode and on our screenshot here in the middle you get the project settings. This is a very important screen that we’ll be just coming back to all the time, even if the project gets really large and complex.

So, as a little wrap-up, you should now know what is a bundle identifier. You should know how to build an app so it runs in simulator and where are the files we will be editing in the next section.

2_orientation
Image 2

Let me write some code already!!!

Ok, you got this far my young padavan, I think you deserve some coding action action now!

In the next couple of steps we will be creating a button that user can click on and a mechanism to make a text label change its content right after the click event occurs.

To do this we will take the simple route at the moment to make it simple for us but later we’ll refactor our code to work solely in code so you get a better understanding of how things actually stitch together.

Open your Main.storyboard file and you should see something like what I’ve got on Image 3 below:

3_storyboard_canvas
Image 3

The first arrow (middle) is pointing at our view controller’s view. This is pretty much our canvas where we’ll place all our visual elements. The other arrow shows the location of your basic element library.

Search the library for a button and place onto a canvas. You can also double-tap the button to change the text on it (you can also do that from the properties inspector on the right.

Now search for label and place it right above the button. Please change the caption of the label to “Number of taps: 0”. See Image 4 for guidance …

4_element_placement
Image 4

So we have the two elements and now we have to be able to connect the logic to them.

Go to the ViewController.h and declare a property that will represent our label and a call to action method for our button as follows:

So we have the header declared, do you see the empty circles next our new property and action? That means that these variables/methods are not connected to their interface builder counterparts. We will have to fix that now.

Go back to the storyboard file and tap on the label once. Once you have tapped the label, you may have noticed how the Utilities/Properties panel has changed.  It now contains number of tabs, some with information and properties of the label, one with positioning and finally one with some strange three items with a tiny little empty circle at the end. You probably still remember when I mentioned the same little circle that appeared next to our newly created variable in the ViewController. And yes, now we have to connect them :)

When you look at the main canvas or your ViewController in the middle section, above it on the controllers bar, you should see a yellowish, button-like circle, that is a representation or our controller. Now grab that empty circle next to labels outlet property and as you drag it over towards the controller icon, you’ll see a strong connection line. Drop it right over the controller and a small popup appears. Just select the variable (property) you have created in the view controller. Once you select it, circles on both sides get a black filling which means they have been connected successfully.

5_connecting_label
Image 5

Now we have to connect our button to the correct action method. In the same manner tap on the button and you shall see many more connection properties. When you look closer, you may notice that there is the same outlet property which we have used with our label. In this case however, we won’t be controlling any property of the button like colour, text or similar. We are only interested in capturing the click event.

There is quite few button events available but we are only interested in one. This event is called “Touch Up Inside”, you might want to play with the other events to get a feel of why the one we selected works best on buttons.

Drag the connection line of our event over the controller’s icon and select the action method we have created.

6_connecting_button
Image 6

What’s next you ask? Well your app is now aware of the label, can capture tap on the button but has no logic inside to process all that. Next step will be adding that logic and to see how you assigning and working with some basic properties in Objective-C and Xcode.

Go to the  implementation file (.m) of your view controller. You should see code similar to the one posted below.

We have some code available to us here, pre-generated by Xcode. On the top we have a private extension of our class. This is extremely useful for declaring variables that the outside world doesn’t have to know about, stuff that is only available inside our class.

First we have to have a variable that we can access at any time from any method in our class so we put @property (nonatomic) NSInteger tapCount; in this private class interface. New we’ll set a default value for our variable when the screen loads. This might not seem to be a completely necessary as the property should be a 0 when you instantiate but I think it is really good to set this somewhere to increase the code readability and well, just to be sure …

We will be setting this in our viewDidLoad method. Code in there will get executed once the screen loads and all elements we have in our storyboard get created.

App logic

Now the interesting bit … till now we have been connecting dots and getting our interfaces ready. Create a method for your button action you have declared in your ViewController’s header file earlier. Best and fastest way to do that (if you don’t feel like copy pasting stuff which you never should do anyway!) is to start typing the method name just right above the viewDidLoad method … so start with dash, space, once you type in no more than “didTap”, the autocomplete should offer you the remainder of the method so just confirm it by pressing return key. Finish it with opening and closing curly braces and we are ready to go to finish the complex logic … the mighty three liner.

So, lets recap what we are trying to achieve here. We would like to tap our button and when we do, increment a number stored somewhere and display a message on our label saying how many taps we did … Simples.

Take a look at the code below to see how this is done:

On the fist line we increment the current value of tapCount by one. On the second we generate and format a string we will than assign to the text property of the label …

Once done, try to run your app and see how nicely the number goes up as you tap the button J … If it doesn’t work you have probably missed something on the go so I’ll put step by step process just as a short recap below:

  • Create project
  • Add Label onto the canvas of our ViewController in Main.storyboard
  • Add a button underneath
  • Create IBOutlet property in your view controller’s header file
  • Create an action for your button there as well
  • Connect labels outlet with your property
  • Connect button’s “touch up inside” event to your action
  • In implementation file setup your counter variable and set it to zero
  • Create a method for your action and put the logic in it.
  • Build an enjoy your creation!

Next we’ll look into other basic elements like switches, sliders and more … stay tuned!

Ondrej Rafaj

Ondrej is a developer, director in several startups and manages XPROGRESS just like that, just for fun!

More Posts - Website - Twitter

Categories: iOS Tutorials, Swift Tutorials, Objective-C Tutorials, Basic Course
Read more:

Post a new comment