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 5: Making it Beautiful

$
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 the fourth part of the series, you created your first simple iPhone app.

In this fifth and final part of the series, how about you take the game from last time and make it look a little more visually appealing?

This part of the series will teach you how to use images for the background of different objects on the screen to spice it up a bit. Also, you will learn how to implement background music and sound effects. Let’s get started!

Getting Started

You’ll start from the project where you left it off last time, so download a copy if you don’t have it already.

I recommend that you make a copy of the project folder before you begin. This way, you will still have your original version of the app before you change what the interface looks like. This is not only good because you can compare your two finished versions, but it also allows you to have the original, working version if you mess up something while trying to change the interface.

Screen Shot 2014-07-28 at 3.56.23 PM

Then, you’ll want to download the Tap Me Resources, which is basically a collection of the images and sounds that you will need for this project. After you download it, you should open up the folder and select all of the items inside. Drag these items over to the Supporting Files folder in your Document Outline.

0Screen Shot 2014-07-28 at 8.24.45 PM

Then, make sure Copy items if needed is selected so that the project will still work on another computer or if you move/delete the resources file from your downloads folder.

1Screen Shot 2014-07-18 at 11.51.19 AM

Setting A Button’s Background Image

Rather than just having your button’s background be a solid color, it looks a lot better when you create an image in a photo editing program. To set the background image, you have to do it based on what state the button is in. Make sure the state of the button is set to default in the Attributes Inspector. This is the state of the button when nothing is happening to it.

1Screen Shot 2014-07-18 at 12.09.50 PM

Then, find the box that mentions the Background, and set it to button_tap_deselected.png

1Screen Shot 2014-07-18 at 12.46.40 PM

In your previous version of the app, you had the background of the button set to be white. Change it back to the default of no color so it doesn’t show behind the image.

1Screen Shot 2014-07-18 at 12.46.49 PM

1Screen Shot 2014-07-18 at 12.47.27 PM

Uh oh! The image is hard to read since the button title is still “Tap Me!”. Since the words are a part of the image, you can go ahead and get rid of the title.

1Screen Shot 2014-07-18 at 12.49.09 PM

1Screen Shot 2014-07-18 at 12.49.25 PM

Much better! Now, the button is legible and looks a whole lot better than it did in your previous version of the app. Rather than a boring white rectangle with some text in it, you now have a 3-dimensional-looking button with colors and better looking text.

Your next step is to set the background image for the same button when it is in the highlighted state. This is the state of the button when it is being clicked by the user. It should have the Background field set to button_tap_selected.png.

1Screen Shot 2014-07-18 at 12.53.47 PM

You may notice your button looks a little bit squished at this point. This is because you have hardcoded width and height constraints that are smaller than the image itself.

Luckily, there is an easy way to fix this. All views have something called an intrinsic content size, which you can think of as an automatic constraint that is set to the size of the element being presented. In the case of an image, it will be the size of the image itself.

So rather than having hardcoded width and height constraints, you can rely on the intrinsic content size of the image to size the image view appropriately.

Let’s try this out. In the document navigator, find the width and height constraints for the button and hit delete to remove them:

DeleteConstraints

Then, update all the frames in your view controller to match their constraints by clicking on the third icon in the bottom right and selecting All Views\Update Frames.

UpdateAllFrames

Build and run, and enjoy your big button!

BigButton

Adding Images to the Screen

Sometimes, you may want to add images to the screen that do not act as buttons. In this case, you can use a UIImageView. Find Image View in the Object Library and drag one onto the screen.

You will be using this Image View object to create a border, so you will want to position and resize it so that it stretches from the left side of the screen to the right side of the screen and touches the top part of the screen. Do the same with another Image View object for the bottom border.

Screen Shot 2014-07-18 at 1.35.13 PM

Note you should move your labels a bit to make room. The easiest way to do this is to just update their constraints using the Edit button in the size inspector:

UpdateConstraint

Using what you learned in the previous section of this tutorial, you should be able to figure out how to set the image of each object and resize it to the size you need. The only difference is the field for setting the image is called Image instead of Background. Set Image to checker_top.png for the top Image View and checker_bottom.png for the bottom Image View. The size for each should be Width as 480 and Height as 22.

Screen Shot 2014-07-18 at 1.36.46 PM

Screen Shot 2014-07-18 at 1.37.05 PM

Screen Shot 2014-07-18 at 1.44.00 PM

Screen Shot 2014-07-18 at 1.47.24 PM














You also need to set up some constraints for these image views. Try to do this on your own, but if you get stuck check the spoiler below! Hint: You will actually want to specify the width and height of the image so it stretches appropriately, not rely on the image size.

Solution Inside SelectShow>

Run the app again and enjoy your beautiful borders!

Borders

Programmatically Setting the Background Color

You don’t always have to go through Storyboard to change the way your app looks. Let’s change the background color to purple to test this out. Try adding this line inside of viewDidLoad() in ViewController.swift:

view.backgroundColor = UIColor.purpleColor()

What this line of code does is it takes the backgroundColor attribute of the view and sets it to the UIColor object returned by the method purpleColor().

Now run the app and check out what it looks like.

Screen Shot 2014-07-18 at 2.01.48 PM

Although this shows proof of concept, it still doesn’t look that great. However, lucky for you, you can also set the background of the view to an image. Let’s do this in the program again. Replace the line where you set the background color to purple with the following:

view.backgroundColor = UIColor(patternImage: UIImage(named: "bg_tile.png")!)

This line tiles the image to fill the background of the view. Run the app to see what it looks like.

Screen Shot 2014-07-18 at 2.02.48 PM

While you’re at it, go ahead and programmatically set the background of both labels as well. To do this, type in the following two lines of code.

scoreLabel.backgroundColor = UIColor(patternImage: UIImage(named: "field_score.png")!)
timerLabel.backgroundColor = UIColor(patternImage: UIImage(named: "field_time.png")!)

Run the app and see what it looks like now.

Screen Shot 2014-07-18 at 2.03.48 PM


Positioning and Sizing Labels

There are a couple things that could use some improvement here. One thing is that the positioning and sizes of the labels are off. scoreLabel is obviously too high up and its size and shape do not fit its image.

To fix this, select the top label and use the Pin button to add constraints to set its width to 133 and height to 46:

TimeConstraints

Then select the bottom label, find its current height constraint in the Project Navigator, and hit delete to remove it:

RemoveScoreCosntraint

Then use the Pin button to add constraints to set its width to 146 and height to 102:

ScoreConstraints

Finally, clear your selection, click the third button, and choose All Views in View Controller\Update Frames to apply the constraints.

One final tweak. The background that you are using for the labels makes it nearly impossible to read black text on. To solve this, change the text color to a light blue that goes well with the rest of the interface. Use these values for the best results. Make sure you do this for both timeLabel and scoreLabel.

Screen Shot 2014-07-18 at 4.53.26 PM

Also set the alignment of each label to center justified.

Now, run the app to see how much easier it is to read the newly colored text!

Screen Shot 2014-08-10 at 11.29.56 AM

Adding Sound

Music and sound effects are great ways to add character to your app. That’s the last thing this app is missing!

But first, you’ll need some sounds. Download these sounds, unzip the file, and the three sound files into your project.

The three sound files are: background music, a beep for every time the player taps the button, and a beep for every second that passes on the countdown clock, just to make the player sweat a little!

The sound playback will be handled from the view controller code, so open up ViewController.swift. Near the top of your file, you’ll notice this line

import UIKit

You will also need to use an import statement for the AVFoundation framework, which is the Apple framework responsible for playing sound and video. Add the following statement immediately following the previous import statement mentioned.

import AVFoundation

Just as importing UIKit lets you use things like UIButton and UILabel, importing AVFoundation lets you use the very useful AVAudioPlayer class. Next, you’ll need an instance variable for each of the three sounds. Add a line for each instance variable just after the declaration of other instance variables inside the class body.

var buttonBeep = AVAudioPlayer()
var secondBeep = AVAudioPlayer()
var backgroundMusic = AVAudioPlayer()

Next, you will need to add this helper method above the viewDidLoad method.

func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer  {
  //1
  var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
  var url = NSURL.fileURLWithPath(path!)
 
  //2
  var error: NSError?
 
  //3
  var audioPlayer:AVAudioPlayer?
  audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
 
  //4
  return audioPlayer!
}

This method will return an AVAudioPlayer object (declared by the ->), and takes two arguments: a file name and type. Let’s look at what it does by section.

  1. You need to know the full path to the sound file, and NSBundle.mainBundle() will tell you where in the project to look. AVAudioPlayer needs to know the path in the form of a URL, so the full path is converted to URL format.
  2. A NSError object will store an error message if something goes wrong when setting up the AVAudioPlayer. Usually nothing will go wrong, but it’s always good practice to check for errors, just in case!
  3. This is the important call to set up AVAudioPlayer. You’re passing in the URL, and the error will get filled in if something goes wrong
  4. If all goes well, the AVAudioPlayer object will be returned!

Now that you have a handy method that will set up AVAudioPlayer objects, it’s time to use it! Add this code to the viewDidLoad() method, at the top of the method before setupGame():

buttonBeep = self.setupAudioPlayerWithFile("ButtonTap", type:"wav")
secondBeep = self.setupAudioPlayerWithFile("SecondBeep", type:"wav")
backgroundMusic = self.setupAudioPlayerWithFile("HallOfTheMountainKing", type:"mp3")

At this point in viewDidLoad, you’ll have all three sounds ready to be called in your code!

The first sound, buttonBeep, should play when the button is pressed. Update the buttonPressed method to play the sound by adding this line at the end of its method body:

buttonBeep.play()

There are two other sounds to add. The secondBeep sound should be played every second when the timer ticks down. Add the call to play that sound in subtractTime() method by adding this line right before the if statement.

secondBeep.play()

You’re almost done!

The final step is to add the background music. To play the music every time a new game is started, add the play code to the setupGame() method. Add these lines to the very bottom of the method body:

backgroundMusic.volume = 0.3
backgroundMusic.play()

You can adjust the volume of the background music so the beeps can still be heard. Changing the volume attribute of the backgroundMusic is a good way to do this. It can be set from 0 (off) to 1.0 (full volume), but 0.3 is a good starting point.

Now run the app for a final time and experience the glory of your fully featured app!

FinalGame

Where To Go From Here?

Congratulations! You have just made your first iPhone app, and taken it from having very basic functionality, to being a polished looking and sounding app. Here is a copy of the finished project for you to compare to your finished project.

There are lots of things that you can modify in your app, such as adding or changing some of the graphics, adding different levels, or even modifying the sound effects – the sky is the limit!

From here, you might want to go through the iOS Apprentice series, which goes much more into depth about making iOS apps. It’s also for complete beginners, and you can get the first part for free by signing up for our newsletter.

In the meantime, if you have any questions or comments, please join the forum discussion below!

Learn To Code iOS Apps With Swift Tutorial 5: Making it Beautiful is a post from: Ray Wenderlich

The post Learn To Code iOS Apps With Swift Tutorial 5: Making it Beautiful appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4370

Trending Articles