Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4370

Learn To Code iOS Apps With Swift Tutorial 4: Your First App

$
0
0
Learn to Code iOS Apps in this Swift Tutorial - for complete beginners to programming!

Learn to Code iOS Apps in this Swift Tutorial – for complete beginners to programming!

Update note: This tutorial was updated for iOS 8 and Swift by Ry Bristow. Original post by Mike Jaoudi.

Congratulations, you made it to part 2 of our Learn to Code iOS Apps with Swift tutorial series!

In the first part of the series, you learned the basics of programming with Swift. You learned about variables, if/else statements, loops, optionals, and more.

In the second part of the series, you put your new Swift skills to the test by making a simple number guessing game.

In the third part of the series, you created a simple command-line app to record the names and ages of people.

In this fourth part of the series, it’s finally time to make your first iPhone App!

In this tutorial, you will learn how to make a simple game called Tap Me! The objective of the app will be to click a button as many times as you can in 30 seconds. Let’s get started.

Getting Started

First, open up Xcode and select Create a new Xcode project.

1-Welcome_To_Xcode_New_Project

Then, select iOS > Application > Single View Application and hit Next.

2-Select_Single_View_Application

Fill out the project options as follows:

  • Product Name: Tap Me
  • Organization Name: This field can be left blank. Or you can enter your company name.
  • Organization Identifier: Enter com.yourname, such as com.rybristow
  • Language: Swift
  • Devices: iPhone

Screen Shot 2014-07-14 at 3.27.26 PM


Storyboards

You’ll notice that this project starts out with different files than your Command Line Tool App. The first one that you are going to want to look at is called Main.storyboard.

02-Select_Storyboard

When you click on this file, it will open up a Graphical User Interface (GUI) that shows what the iPhone screen will look like when it runs the app.

03-Blank_View_Controller

Note: You may wonder why the screen looks like a square, instead of the iPhone size. In iOS development, your goal is to design your apps so that they can adapt to different screen sizes – this is called Adaptive Layout.

Basically, you lay out your user interface elements with rules like “stay this far away from the top” or “stay centered”; this way it can work on different screen sizes, from iPhone 5 to iPhone 6 Plus and so on.

Right now, the app is just plain white and boring. To make some changes to this, you have to make sure that the Utilities Menu is open. Make sure it is selected and open.

04-Utilities_Menu

Next, select the Attributes Inspector. This allows you to view and edit different attributes that have to do with the View Controller. Make sure you click on the view first to be able to view the attributes.

05-Attributes_Inspector

Let’s make it a little more interesting to look at. Change the background color to green so it’s not plain white.

06-Change_Background_Color

Now, in the menu up top choose the iPhone 6 Simulator and run the app so you can take a look at what it will look like. It may take a while to build and run, so be patient. When it finally runs, you should see a window pop up that simulates the screen of an iPhone running this app.

07-First_Run


Adding Labels to the Screen

A green screen is great and all, but your app is pretty much useless if it doesn’t have anything on the screen for the user to interact with. To add objects, you have to go to the Object Library in the Utilities Menu. The first object you should add is called a Label. Labels are just text that can be set by the program. Scroll through the Object Library until you find the Label.

08-Object_Library

Drag it onto the screen and line it up at the top center.

09-Label

You can use the Attributes Inspector to change the title of the Label which changes what the Label says. Change the title to “Time: 30″.

10-Change_The_Title

At this point your label might look truncated on screen. To fix this, click your label and choose Editor\Size to Fit (Command =).

Now, run the app and see what it looks like.

12-Not_Centered

According to your storyboard, the Label looks as though it should be centered, right? The problem is that not every iOS device has the same dimensions, so it can get messed up sometimes. What you need to do is add a constraint to the label to get it to stay in the center of the screen.

To do this, first click on the Label. Then, select the Align button at the bottom of the screen and select Horizontal Center in Container and then Add 1 Constraint.

13-Adding_Horizontal_Constraints

That determines where the label should be placed horizontally. But you need to specify where it is vertically as well. To do this, click the Pin button at the bottom of the screen and click the red bar to pin it to the top, based on its current distance and click Add 1 Constraint:

TopConstraint

Now, make another Label to be placed at the bottom of the screen to keep track of the score. The only two differences are that you are going to want the font size to be 40, the lines to be 2, and you want it 130 points tall.

14-15-Changing_Font_Size

You need to set up some constraints for this as well. See if you can figure it out on your own, but if you get stuck check the solution below!

Solution Inside SelectShow>

Build and run, and now your labels should be nicely centered:

CenteredLabels

Add a Button

To add the last object that you need to the screen, use the Object Library to add a button to the screen and position it at the very center.

16-17

Don’t forget to add constraints to the button, this time for both horizontal and vertical centers.

18-Centering_Constraints

Now, use the Attributes inspector to change the title to “Tap Me!” and the Background to a white color.

19-20

In order to get the button to actually show off more of its white background, you need to stretch it out more and then set different kinds of constraints on it. This time, you have to click on the button that says Pin and then click on the boxes that say Width and Height.

23-Constrain_Button_Size

After you do this, your button might be small with an orange border around it, representing that its current size does not match its constraints. To fix this, click the third button at the bottom and choose Update Frames:

UpdateFrames

Your button should be a nice big tappable area. Build and run, and your app should look like the following:

TappableButton

You can tap the button, but nothing happens yet. You’ll fix that next!

Linking Views to Code

Now that you have laid out your views in the Storyboard, you need to hook them up to code.

Each “screen” of an iOS app is controlled by a class called a View Controller. Xcode has already created one of these for you in the template – ViewController.swift.

You need to add two properties to this class for the labels in your game, so you can update them programmatically. To do this, add the following new properties in the ViewController class in ViewController.swift:

@IBOutlet var scoreLabel: UILabel!
@IBOutlet var timerLabel: UILabel!

These two lines create two UILabel properties. In a moment, you will hook up the views you created in the Storyboard to these properties. By marking these properties with the special @IBOutlet keyboard, the storyboard editor becomes aware of them.

Note: You might notice that you mark the labels with an exclamation point at the end. This makes the labels “implicitly unwrapped optionals”. This makes the compiler automatically unwrap the optionals before you access them, so you can treat them as-if they weren’t optional variables (even though they are).

It’s OK to do that in this case because you’re sure you’ll be setting these to the views you created in your storyboard so they won’t be nil.

Similarly, you’d like a method to be called when the button is pressed. So add the following method to the ViewController class:

@IBAction func buttonPressed()  {
  NSLog("Button Pressed")
}

Just like with @IBOutlet, @IBAction makes the storyboard editor aware of this method, so you can link the button tap event to it.

Let’s try hooking up these properties and method! Open up Main.storyboard, and check out the Document Outline. What you need to do to connect the labels is CTRL-drag from View Controller in the Document Outline to the Time label up top.

HookingUpTimeLabel

A small black box will pop up listing the Outlets. Select the one called timerLabel. This is the UILabel object that you created in the ViewController.swift file.

Screen Shot 2014-07-15 at 10.04.17 PM

Now repeat this for the score label, but hook it up to scoreLabel instead.

To connect the button to the method buttonPressed(), you have to go in the opposite direction. CTRL-drag from the button in the Storyboard to View Controller in the Document Outline.

HookingUpButton

Then, select buttonPressed().

Screen Shot 2014-07-16 at 8.33.03 PM

Now, try running the app and pressing the button a few times. Due to the NSLog statement that you used in the buttonPressed() method, the console at the bottom of the screen that you have used in previous projects should have an output every time you click the button.

24-Run_App_With_Buttons

Manipulating Labels

The real purpose of the button will not be to output a statement to the console, but to change what the core label says to add a point to it each time it is pressed. First, you should learn how to manipulate the text in a label.

Good news – it’s easy! Replace the body of buttonPressed() with the following code.

scoreLabel.text = "Pressed"

Now, when you run your app and press the button, the text at the bottom of the screen should change to say “Pressed”.

In order to use this skill to make scoreLabel keep track of the score, you will need to do a bit more work.

Keep Track of the Score

To keep track of the score, you first need to create a variable to do so. Up near the top of the class body, underneath the two @IBOutlet declarations, create a property called count to keep track of the score.

var count = 0

The next step is to insert a line of code to increment count into the top of buttonPressed():

count++

This line is the shortcut for saying:

count = count + 1

Now, change the line that sets the text of scoreLabel to:

scoreLabel.text = "Score \n\(count)"

Run your app and test it out again. When you click the button, the label at the bottom of the screen will keep track of your score. Your app is getting closer and closer to becoming a playable game!

Working with the Timer

To get the timer to work correctly for this app, you will need to create two new properties. One of these variables should be an int that keeps track of the seconds and a NSTimer variable to count down.

Add these declarations right underneath the declaration for count.

var seconds = 0
var timer = NSTimer()

In order to use these variables, you will need to create two methods. The first will be called setupGame(). Write the following method at the bottom of your class body.

func setupGame()  {
  seconds = 30
  count = 0
 
  timerLabel.text = "Time: \(seconds)"
  scoreLabel.text = "Score: \(count)"
}

This code sets everything back to its original values when the game begins and updates the labels. If you didn’t include this code, then the seconds would continue decreasing past 0 and the score would just keep adding on for the next game and never reset.

The next step for the setupGame() method is to start the timer. To do this, you use the method scheduledTimerWithTimeInterval() to get the timer to do what you want. Include this code in the setupGame() method.

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("subtractTime"), userInfo: nil, repeats: true)

Now, make sure that you call the setupGame() method in the viewDidLoad() method by adding the line:

setupGame()

The next method that you need to write should be called subtractTime(). You will notice that you used this phrase in the selector spot when you worked with the timer in setupGame. This is what it is referring to. This method will be used to decrement the seconds variable, update the timeLabel, and cause an alert to pop up when the timer reaches 0.

Let’s start out with the things you already know how to do: decrement seconds, update timerLabel, and create an if statement for when seconds reaches 0.

func subtractTime() {
  seconds--
  timerLabel.text = "Time: \(seconds)"
 
  if(seconds == 0)  {
 
  }
}

The first thing you will want to add to the body of the if statement is something to stop the timer from counting past 0. Use the following line of code to do so:

timer.invalidate()

Build and run your game, and now the time should count down!

Countdown

Red Alert!

Next, you’ll learn how to work with alerts. When you finish coding your alert, it should look like this:

Screen Shot 2014-07-17 at 7.04.25 PM

Let’s get started. The first thing you are going to do is create a UIAlertController. Insert this line after the invalidate() statement inside the if statement.

let alert = UIAlertController(title: "Time is up!",
 message: "You scored \(count) points",
 preferredStyle: UIAlertControllerStyle.Alert)

This line determines what the alert will look like. It specifies the title, message, and style of the alert.

Next, you will need to adjust what the button says and does. To do this, you use addAction(). Type this line after the declaration of alert.

alert.addAction(UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {
  action in self.setupGame()
}))

If you examine this line closely, you see that it uses title to determine what the button says, and you will see that handler makes the button call the setupGame() method when the button is pressed and the alert is dismissed.

Time for the last line of code! This line is what actually tells the app to present the UIAlertController. It uses presentViewController(). Type this line after alert.addAction(...).

presentViewController(alert, animated: true, completion:nil)

Now run the app and enjoy your very first iPhone app. Can you beat my score? :]

TopScore

Where to Go From Here?

The final project with full source code can be found here.

You’re now ready to move on to the next tutorial in this series, where you’ll learn how to clean up the look of your app and make it more visually appealing.

If you have any question or comments, come join the discussion on this series in the forums!

Learn To Code iOS Apps With Swift Tutorial 4: Your First App is a post from: Ray Wenderlich

The post Learn To Code iOS Apps With Swift Tutorial 4: Your First App appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4370

Trending Articles