游戏邦在:
杂志专栏:
gamerboom.com订阅到鲜果订阅到抓虾google reader订阅到有道订阅到QQ邮箱订阅到帮看

写给中学生和新手的iOS应用制作教程(2)

发布时间:2013-06-04 10:01:43 Tags:,,,,

作者:Mike Jaoudi

第一部分文章中,你创造了一款简单但却有趣的游戏,能够让你快速地敲击按键。

但是现在的应用看起来还不是很如意!所以在本篇教程中你将继续完善它。

具体说来便是,你将学习如何添加定制图像和声音,从而让玩家能够感受到其他iOS应用中所具有的那般游戏体验。

今天的教程将连接着之前的教程,所以你需要先浏览之前的内容。

为何如此费心?游戏已经完成了!

你可能会想:“为什么要费心去做这些事呢?为什么要添加定制图像和声音到游戏中?我还有更重要的事要做,如Xbox!”

让我们着眼于下图,你是否仍具有相同的看法:

screen(from raywenderlich)

screen(from raywenderlich)

你认为哪款应用更能吸引玩家花钱?

左图是我们在第一篇教程中所创造的——而右图则是添加了定制图像和声音后的样子。就像你所看到的,你在本篇教程中所付出的额外努力将能让应用变得更加完善,并且你也能够从中学到更多内容!

添加定制图像到应用中能够赋予其更加出色且专业的外观。要记住,你的应用将与数百万应用展开竞争。看起来直观且讨喜的应用外观总比直观讨喜的代码来得重要!

双倍密度

一开始我们需要下载该项目的资源。多谢Vicki Wenderlich创造了这些图像。

在下载了文件后,你需要解压文件,并着眼于其中的图像:

images(from raywenderlich)

images(from raywenderlich)

我们可以注意到,每个图像都拥有两个副本。较小的图像是用于基于常规现实的设备(较早的iPhone和iPad),而另外的图像则为了Retina显示屏(新iPhone和iPad的显示屏)而提高了高度与宽度。

Retina显示屏的密度是非Retina显示屏的2倍,也就是20×20(400像素)的图像需要变成40×40规格(1600像素)才能利用优质的Retina显示屏。较新的iOS设备便具有Retian显示屏,所以开发者有必要包含更高分辨率的图像。

如果你只在文件中包含常规分辨率的图像会怎样?在这种情况下,你的应用将显得非常模糊,就像如下:

blurry(from raywenderlich)

blurry(from raywenderlich)

处理包含多种版本图像的文件并不需要额外的代码。

苹果使用的是特定文件命名约定,即你只需要在扩展前于文件名称最后添加““@2x”便可。举个例子来说吧,如果你拥有一个名为image.png的文件,那么其retina版本文件名便为image@2x.png,如下:

retina version(from raywenderlich)

retina version(from raywenderlich)

然后当你在编写代码或使用故事板时,你只需要参考图像名称是否包含@2x便可。应用将能够明确其所运行的设备类型。

开始

运行Xcode并从第一部分教程中打开项目。

首先你需要添加所有图像和声音到项目中。为了做到这点,你需要从文件夹中选择所有条目,让后将其拖到Xcode中你的所有文件所在区域。你必须将图像和声音资源放置在Supporting Files群组中,如下:

group(from raywenderlich)

group(from raywenderlich)

确保你选中了“Copy Items into Destination Group’s Folder”,然后点击完成。

group(from raywenderlich)

group(from raywenderlich)

选择“复制项目”选项框,Xcode将复制所有图像并将其储存在你的项目库存中。这一步非常重要,因为即使你将文件从原始位置(即下载的地方)上删除,或移动文件夹时,你的项目也能继续运行。这是一个很棒的实践,能够确保Xcode项目所需要的一切内容都放置在库存中。

现在所有的声音和图像都已经安置在项目中了,并且即将发挥功效。而因为你正在操控项目的全新图像元素,所以你必须在故事板布局中运行它们。

图像在传达故事

下图便是你的故事板,即你在本教程第一部分中所遗留下来的内容。我们首先需要改造的便是“Tap Me”按键。选择该按键并着眼于右边栏上的属性。要记得,属性标签是左起第四个图标,看起来有点像是滑动器:

attributes(from raywenderlich)

attributes(from raywenderlich)

在顶部列表中找到按键的状态配置属性:

state config(from raywenderlich)

state config(from raywenderlich)

在你的应用中,按键将拥有不同的状态。在此你的按键可能拥有四种不同的状态:默认,突出,选中,无效。

states(from raywenderlich)

states(from raywenderlich)

默认–按键未被按压

突出–按键被按压

选中–按键被开启,但却未被按压。例如用于“触发器”开关

无效–按键不能被按压

你最常使用的将是默认和突出–因为它们意味着被按压与未被按压。

的确,“轻敲我”的按键与默认和突出状态具有不同的外观。你需要确保将状态配置设为默认,然后设置背景属性为button_tap_deselected.png。要记住你现在正在使用没有@2x的文件名。

DefaultImage(from raywenderlich)

DefaultImage(from raywenderlich)

现在可以看看你所创造的全新游戏按键了!

new game button(from raywenderlich)

new game button(from raywenderlich)

啊,这看起来有点糟糕。按键带有两个重叠的名字!接下来我们该怎么做!

图像和按键都拥有文本指示着行动。你需要关掉按键的名称。在图像的属性中将“轻敲我”删除。

title(from raywenderlich)

title(from raywenderlich)

这时候的按键看起来就好多了,但是尺寸却有点别扭。该如何做才能创造出一个好看的圆形按键呢?

button(from raywenderlich)

button(from raywenderlich)

你可以在故事板上直接调整按键的尺寸,但是这时候你的设计感应该发挥一定的作用。要记住,你现在所面对的是拥有精确尺寸的图像:就像在这个例子中是228×240像素。你可以将按键的准确尺寸整合到故事板上。

确保你仍然选择了按键,并转向右边栏中的尺寸标签。这是右边起第二个按键,并拥有一个尺子般的图标:

size(from raywenderlich)

size(from raywenderlich)

将宽度改为228,高度改为240。

width and height(from raywenderlich)

width and height(from raywenderlich)

现在的按键图像看起来就很好了!确保在故事板中将按键的位置设于屏幕中央,并确保不会与屏幕上的其它两个标签重叠。

button image(from raywenderlich)

button image(from raywenderlich)

现在按键的尺寸和位置便设置好了,你仍然需要改变按压按键时它所呈现出来的样子。为了做到这点,你需要使用不同图像去呈现被压住的状态。

回到属性标签,并将状态配置设为突出,如下:

highlighted(from raywenderlich)

highlighted(from raywenderlich)

现在将背景设置为button_tap_selected.png

background(from raywenderlich)

background(from raywenderlich)

现在的新按键看起来已经很棒了!点击左上方的运行按键,并观看它的运转:

new button(from raywenderlich)

new button(from raywenderlich)

棒极了!基于新添加的图像,你的应用看起来好多了。

相比较起来,应用的其它部分看起来略显老旧,不是吗?所以你也需要花时间去改造其它内容。

图像视图

你已经知道如何添加图像作为按键背景了,但是如果你不需要按键并只需要图像的话该怎么办?这时候图像视图将派上用场!顾名思义,图像视图也就是能够呈现图像的视图。

听起来就像你可以使用视图而更好地呈现应用!进入目标程序库并将图像视图拖到故事板上,如下:

storyboard(from raywenderlich)

storyboard(from raywenderlich)

如果你在屏幕的上下方设有边界的话这会看起来很棒——你将能够呈现出一种棋盘式的格局。

将图像视图拖到主视图中。将一个放置在主视图上方,另一个置于视图下方。你将在之后更精确地设置宽度和高度,所以此时你只需要大概地调整尺寸,让它们显得较短便行,如下图:

button(from raywenderlich)

button(from raywenderlich)

很好!现在你需要基于每个图像视图设置图像呈现。点击最上方的图像视图并来到属性列。将图像设置为checker_top.png。

image(from raywenderlich)

image(from raywenderlich)

现在你将需要设置图像视图在屏幕上的准确尺寸。来到尺寸标签。将宽度设置为320,高度设置为23。

size(from raywenderlich)

size(from raywenderlich)

现在看起来更棒了。你只需要遵循同样的方法去设置底部图像视图便可。

点击地图图像视图并前往属性栏,然后将图像设置为checker_bottom.png,如图所示:

image(from raywenderlich)

image(from raywenderlich)

现在设置底部图像视图的尺寸。前往尺寸标签,将宽度设置为320,高度设置为22。

size(from raywenderlich)

size(from raywenderlich)

现在我们可以在应用上检查其表现了!点击左上方的运行按键:

button(from raywenderlich)

button(from raywenderlich)

到目前为止一切都很顺利。你的应用越来越完善了,但是背景那刺眼的绿色仍然存在着,现在你需要用适当的新图像去替换它。

重新回到背景

在第一部分教程中,我们已经将主视图的背景色设为绿色。尽管设置背景颜色很简单,但是在故事板中却不存在一种真正简单的方法能够有效设置背景图像。我们是时候离开故事板一会,而回到代码中了!

打开ViewController.m,并着眼于viewDidLoa的方法。我们需要记住这一方法是在创造了所有视图后所调用的方法。并且是在所有视图呈现在屏幕上之前所调用的方法。

这听起来像是设置背景图像的最佳位置!

当你想要改变呈现在标签上的文本时,你必须使用IBOutlet关键字去设置中心点。而现在,当你想要改变背景视图时,你是否需要为背景图像设置另一个中心点?

并不需要——幸运的是,项目能够为你自动设置中心点,所以你可以继续前进并改变背景颜色。更新你的viewDidLoad方法如下:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.view.backgroundColor = [UIColor purpleColor]; // ADD THIS!!

[self setupGame];
}

因为这是ViewController,self代表视图控制器;view指的是背景;而backgroundColor则是关于视图背景颜色。

运行你的应用!现在你将能够看到如下紫色的背景了:

color(from raywenderlich)

color(from raywenderlich)

好消息是,现在的你已经知道如何通过代码设置背景色了。

那坏消息是什么?那就是紫色看起来还是很奇怪!我不认为它比绿色正常多少。

UIColor拥有一个巧妙的装扮技巧:除了固定的颜色外,它能够将任何图像转变成你可以用于背景中的模式!如果图像小于背景,它将重新进行拼贴,从而让图像能够覆盖完整的视图。

也许该功能可以帮你改变这奇怪的紫色背景?

在viewDidLoad中改变背景颜色,如下:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_tile.png"]];

比起像绿色或紫色这样特定的颜色,你也可以调用colorWithPatternImage从图像中获得一个模式。图像被当成UIImage对象储存着,所以在此你可以使用bg_tile.png图像去设置UIImage,这将成为应用的背景。

现在运行你的应用—-是否看起来好多了?

color(from raywenderlich)

color(from raywenderlich)

是的,看起来顺眼多了!如果你未看到好看的背景图像,你便需要确保是否在代码中准确拼写了文件名称。

在你的应用中可以使用两个背景图像:一个是用于计时器标签,另一个则是用于分数标签。

在viewDidLoad方法上添加以下两行代码(游戏邦注:即在你设置视图背景之后):

scoreLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"field_score.png"]];
timerLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"field_time.png"]];

除了视图使用不同的图像外,我们基于同样的方法准确设置了模式。

现在运行你的项目:

pattern(from raywenderlich)

pattern(from raywenderlich)

但是现在仍存在着问题,即文本比之前更难阅读了。

如果背景图像小于视图,UIColor将通过拼贴而帮助你解决问题,但是如果背景图像过大的话,你就只能进行裁剪了。

就像你在故事板上设置了“轻敲我”的按键尺寸一样,你也可以如此去设置这两个标签。打开MainStoryboard.storyboard并选择计时器标签。在在工具栏的尺寸标签中,设置宽度为133,高度为46,如下:

size(from raywenderlich)

size(from raywenderlich)

对于分数标签也是如此。选择分数标签,设置宽度为146,高度为102,如下:

score label(from raywenderlich)

score label(from raywenderlich)

现在运行应用看看。

button(from raywenderlich)

button(from raywenderlich)

虽然有所好转,但是文本还是很难阅读。也许在深色背景中浅色的文本内容会更明显?

打开Mainstoryboard.storyboard,选择计时器标签。在属性栏中点击颜色旁的黑色块以打开调色板,如下:

SetColor(from raywenderlich)

SetColor(from raywenderlich)

在调色板中选择滑动条标签,然后从拉下式选单中选择RGB滑动条。如此你便能够分别进入标签的红色,绿色和蓝色值中。

将红色设置为190,绿色为255,蓝色为255,如下:

color(from raywenderlich)

color(from raywenderlich)

分数标签也遵循同样的方法。选择分数标签,在属性中点击颜色而打开调色盘,然后将红色设为190,绿色为255而蓝色为255,如下:

color palette(from raywenderlich)

color palette(from raywenderlich)

现在运行项目!效果如何?

button(from raywenderlich)

button(from raywenderlich)

看起来更好了!现在你不仅创造了自己的第一款iOS应用,同时你也创造了一款外观出色的应用!

但是应用并不只是外观好看就够了,它也需要有合适的声音。为了对应用进行最后优化,你需要添加一些音乐和音效。

添加声音

音乐和音效是赋予应用特色的一种好方法。在应用中你需要使用三种声音:背景音乐,玩家敲击按键所发出的声音以及倒计时的哔哔声(游戏邦注:能让玩家感到紧张)。

iOS支持各种类型的功能,如GPS,加速器以及声音回放。这些功能奖杯整合到框架中。你已经使用名为UIKit的框架,其中包含了视图,视图控制器,按键和故事板等内容。

为了播放声音,你需要使用名为AVFoundaton的框架。将其添加到项目中,点击左边工具条文件浏览器最上方的“轻敲我”项目,如下:

Tap Me(from raywenderlich)

Tap Me(from raywenderlich)

然后点击目标中的“轻敲我”,并选择总结标签:

summary tab(from raywenderlich)

summary tab(from raywenderlich)

向下滚动,直到你发现名为Linked Frameworks and Libraries的区域。这是你的应用当前所拥有的所有框架的列表。为了添加更多框架,你需要点击“+”按键。

frameworks(from raywenderlich)

frameworks(from raywenderlich)

现在你便可以选择许多框架了。

在列表中找到AVFoundation.framework并选择它。然后点击添加按键,如下:

list(from raywenderlich)

list(from raywenderlich)

赞!现在的AVFoundation框架已经被添加到项目中了。这时候你将准备播放一些声音了!

我们将使用视角控制器代码去回放声音,所以第一步便是设置页眉文件。打开ViewController.h。在文件上方附近,你将注意到这行内容:

#import <UIKit/UIKit.h>

UIKit框架带有输入语句。为AVFoundation添加另一个输入语句,,从而让代码如下:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

只是输入UIKit的话你便能够使用像UIButton和UILabel,而输入AVFoundation则让你能够使用非常有用的AVAudioPlayer类。

接下来你需要为三个声音分别设置实体变量。为每个实体变量添加一行内容:

@interface ViewController : UIViewController<UIAlertViewDelegate> {
IBOutlet UILabel *scoreLabel;
IBOutlet UILabel *timerLabel;

NSInteger count;
NSInteger seconds;
NSTimer *timer;

// Add these AVAudioPlayer objects!
AVAudioPlayer *buttonBeep;
AVAudioPlayer *secondBeep;
AVAudioPlayer *backgroundMusic;
}

这是面对页眉文件。现在便可以播放一些声音了。打开ViewController.m,并在viewDidLoad方法上添加这一新方法:

- (AVAudioPlayer *)setupAudioPlayerWithFile:(NSString *)file type:(NSString *)type
{
// 1
NSString *path = [[NSBundle mainBundle] pathForResource:file ofType:type];
NSURL *url = [NSURL fileURLWithPath:path];

// 2
NSError *error;

// 3
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

// 4
if (!audioPlayer) {
NSLog(@”%@”,[error description]);
}

// 5
return audioPlayer;
}

这一方法将回到AVAudioPlayer项目中,并包含两个参数:文件名称和类型。让我们一节一节地进行分析:

1.你必须知道声音文件的完整路径,[NSBundle mainBundle]将告诉你着眼于项目中的哪些内容。AVAudioPlayer需要了解以URL形式呈现出来的路径,所以完整的路径将被转变成URL形式。

2.如果在设置AVAudioPlayer时出现了某些误差,那么NSError对象将储存这一错误信息。通常情况下是没有多大问题,但在这个例子中这却是检查错误的好办法。

3.这个是设置AVAudioPlayer的重要方法。你正在进入URL,如果某一环出现错误,那么所有错误将迅速将其填满。

4.如果出现错误,audioPlayer将被设置为零,你便能够基于感叹号进行检查。如果出现这种情况,错误奖被带到主机上。

5.如果一切进展顺利,AVAudioPlayer对象将被送回来!

现在你便拥有一个能够设置AVAudioPlayer对象的便利方法,现在也是时候能够使用它了。在设置背景图像后将如下代码添加到viewDidLoad方法中:

buttonBeep = [self setupAudioPlayerWithFile:@"ButtonTap" type:@"wav"];
secondBeep = [self setupAudioPlayerWithFile:@"SecondBeep" type:@"wav"];
backgroundMusic = [self setupAudioPlayerWithFile:@"HallOfTheMountainKing" type:@"mp3"];

这时候在viewDidLoad中,你将拥有3种能够被调用的声音!

第一个声音buttonBeep将在你按压按键时进行播放。更新buttonPressed方法去播放这一声音:

- (IBAction)buttonPressed {
count++;

scoreLabel.text = [NSString stringWithFormat:@"Score\n%i", count];

// add this line
[buttonBeep play];
}

运行项目进行测试。你将在轻敲按键时听到一个清脆的哔哔声!

还需要添加两种其它声音。当计时器开始运转时便会响起secondBeep的声音。在subtractTime方法中添加调用去播放声音:

- (void)subtractTime {
seconds–;
timerLabel.text = [NSString stringWithFormat:@"Time: %i",seconds];

// add this line
[secondBeep play];

// …the rest of the method continues here…

再次运行项目进行测试。当开始倒计时时,如果你能够听到不同的哔哔声的话,你便算完成了设置。

最后便是添加背景音乐。为了在每次开始新游戏时播放音乐,你需要在setupGame方法上添加播放代码。在setupGame底部添加如下代码:

[backgroundMusic setVolume:0.3];
[backgroundMusic play];

你可以调整背景音乐的音量,从而确保玩家也能够听到哔哔声。setVolume方法将在0(关闭)到1.0(最大音量)范围内;0.3便是背景音乐的最佳起点。

现在运行项目,你将能够感受到应用的完整体验!

总结

恭喜你!你已经创造了自己的第一款应用,并添加了一些基本功能,使之成为一款兼具出色外观和声音的优秀应用。

不过在应用中还有许多需要修改的内容,如添加或改变一些图像,添加不同难度的关卡,或修改音效等等。

本文为游戏邦/gamerboom.com编译,拒绝任何不保留版权的转载,如需转载请联系:游戏邦

iOS for High School Students: Making Your First iOS App: Part 2/2

By Mike Jaoudi

Welcome back to the iOS for High School Students: Making Your First iOS App Tutorial series!

In the first part of the series, you created a simple but fun game where you furiously tried to tap a button as fast as possible.

However, the app didn’t look all that good! In this tutorial, you’ll take that app and add some awesome-sauce to it :]

Specifically, you are going to learn how to add custom images and sounds to the game to give the player the sharp gaming experience they are used to from other iOS apps.

This tutorial will pick up where the last tutorial left off. If you don’t have it already, here’s the project you developed in the previous tutorial.!

Why Bother?! The Game is Done!

You may be thinking “Meh, why bother working on this anymore?! No new features are going to be added to the game. Why does the game need custom images and custom sound?! I have better things to do… like Xbox!”

Well, take a look at this next picture, and see if you still have the same impression:

Which app do you think someone would be more likely to buy? :]

The picture on the left is the end result of Part 1 — the image on the right is the result of adding custom graphics and sound. As you can see, the extra effort you’ll expend in this tutorial to extend your app will definitely be worth it – plus you’ll learn a lot along the way!

Adding custom images to your app will always give it a more polished and professional appearance. Remember, your app is competing with a million others; an app that is intuitive and pleasing to look at is almost as important as intuitive and pleasing code! :]

Double Density

To get started, download the resources for this project. Many thanks to Vicki Wenderlich for making these images!

After you download the file, unzip it and take a look at the images stored inside:

Notice how there are two copies of each image. The smaller image is used for devices with regular displays (older iPhones and iPads) and the other is scaled to double the height and width for Retina displays (the crisp display on newer iPhones and iPads).

The Retina display density is twice that of a non-Retina display, so a 20×20 image (with 400 pixels) needs a 40×40 image (1600 pixels) to take advantage of the high-quality Retina display. Newer iOS devices have Retina displays so it’s important to include these higher-resolution images.

What happens if you only include the normal resolution files, you ask? In that case, images in your app will look slightly blurry or blocky, as in the example below:

Handling multiple versions of graphics files must require extra coding, right? Nope! (Chuck Testa!) :]

Apple uses a special file naming convention where you just add “@2x” to the end of your file name before the extension. For example, if you have a file named image.png, the retina version would be named image@2x.png, as below:

Then when you’re writing code or using storyboards, just refer to the image name without the @2x added onto it. The app will figure out what kind of device it’s running on and automatically pick the retina version if it’s available! Pretty slick! :]

Getting Started

Start Xcode and open up the project from Part 1. Again if you don’t have it already, you can snag it here.

First, you’ll add all of the images and sounds to the project. To do this, select all of the items from the folder to where you downloaded them previously, and drag them into the area where all your files are in Xcode. It makes the most sense to put your graphical and sound resources in onto the Supporting Files group, as below:

Make sure that you check the box at the top that says Copy Items into Destination Group’s Folder, then click Finish.

By selecting the “Copy items” checkbox, Xcode will make a copy of all the images and store it in your project directory. This is important because it will make your project still work even if you delete the files from their original location where you downloaded them, or move that folder somewhere else. It’s a good practice to keep everything an Xcode project needs inside its directory.

Excellent! Now all of the sounds and images are in the project and ready to be used. Since you’re manipulating the new graphical elements of your project, it will make sense to work with them in your Storyboard layout! :]

Images that Tell a Story(board)

Below is your storyboard, just as you left it from Part 1 of this tutorial. The “Tap Me” button will be the first thing to get a makeover. Select the button and have a look at its Attributes in the right sidebar. Remember, the Attributes tab is the fourth from the left and looks like a little slider:

Find the State Config attribute for the button near the top of the list:

Buttons can have several different states in your application. There are four different states that your button can have: Default, Highlighted, Selected and Disabled.

Default – The button is not pressed

Highlighted – The button is pressed

Selected – The button has been switched on, but does not have to be pressed. Used for “toggle” switches for example.

Disabled – The button has been disabled and cannot be pressed
The ones you’ll use most often are Default and Highlighted – since they mean pressed and unpressed.

And indeed, the “Tap Me” button will have a different look for the Default and Highlighted states. Make sure the State Config is set to Default, and then set the Background attribute to button_tap_deselected.png. Remember, you are using the filename without the @2x added onto it!

Now take a look at your fancy new game button!

Uh…that looks terrible! The button has two overlapping titles! What’s going on here?!

Ah — the image AND the button both have text indicating the action. You need to turn off the button title. In the attributes for your image, delete the “Tap Me” text from the Title.

The button looks better -but the sizing is a little off. What should be a nice circular button is a little squished! :]

You could resize the button directly in the storyboard just by looking at it, but your design sense should be tingling at this point. Remember, you’re dealing with an image that has an exact size: 228 by 240 pixels, in this case. It makes sense to enter the exact size of the button right into the storyboard.

Make sure the button is still selected, and switch to the Size tab in the right sidebar. It is the second button from the right and it has a ruler icon:

Change the Width to 228 and the Height to 240.

Hey — the button image now looks great! Make sure to position the button on the storyboard to the center of the screen, and make sure it isn’t overlapping the other two labels on the screen.

Okay! Now that the size and positioning of the button is set, you still need to change what the button looks like when it’s pressed. To do that, you will use a different image to represent the depressed state.

Go back to the Attributes tab and set the State Config to Highlighted, as below:

Now set the Background to button_tap_selected.png

Great — it looks like your fancy new button is ready to go! :] Click the Run button in the upper left corner and see it in action:

Wonderful! Your app is starting to look a lot better with that one set of images added!

The rest of your app is looking a little dated in comparison, isn’t it? Time to give the rest of it a makeover! :]

Image Frenzy!

You’ve just learned how to add images as button background images — but what if you don’t need a button and just want the image? Image Views to the rescue! As the name suggests, an Image View is a view that can display images.

Awesome! Sounds like you can use an Image View to make your app look even better! Go into the object library and drag an image view into the storyboard, like so:

It would look nice if you had some borders at the top and bottom of the screen — a nice checkerboard pattern has been provided for you.

Drag an Image View into the main view. Place one at the top of the main view, and one along the bottom of the view. You’ll set the width and height more precisely in just a moment, so just roughly resize them to stretch across the width of the view and make them a little shorter, as pictured here:

Super! Now you need to set the image to be displayed in each of the two Image Views. Click on the top image view and go to the Attributes column. Set the Image to checker_top.png.

Now you’ll need to set the Image View to be the the correct size for your screen. Go to the Size tab. Set the Width to 320 and the Height to 22.

That looks a bit better! Now you just need to do the same thing to the bottom Image View.

Click on the bottom image view and go into the Attributes column. Then set the Image to checker_bottom.png, as shown:

Now set the bottom Image View to the proper size! Go to the Size tab, and set the Width to 320 and the Height to 22.

Time to check out how things look in the app! Hit the Run button in the upper left corner:

So far so good! Your app is starting to look better — but that awful green color in the background is a real bummer, now that you have your shiny new graphics in place!

Time to repaint the walls of your app! :]

Backgrounds, Revisited

In Part 1, you set the background color of the main view to green. While setting a background color is easy, there isn’t a real easy way to set a background image right on the storyboard. Time to leave the world of storyboards for a bit and return to the code!

Open up ViewController.m and have a look at the viewDidLoad method. Remember that this method is called right after all the views are created. It is also called before all of the views are displayed on the screen.

Hm…this sounds like the perfect place to set up your background image! :]

When you wanted to change the text displayed in a label, you had to set up outlets with the IBOutlet keyword. Now, you want to change the background of the view. Do you need to setup another outlet for the background image?

No — fortunately, the project automatically sets up an outlet for you, so you can go ahead and change the background color. Update your viewDidLoad method like this:

Since this is a ViewController, self refers to the View Controller; the background view is view; finally, the view’s background color is backgroundColor.

Note: In code, you refer to color by way of the UIColor class. Colors are typically stored as separate red, green and blue (RGB) values, since any color can be those three basic colors in various combinations. Rather than mix and match color values, UIColor has some built-in shortcuts such as purpleColor that you’re using here, just to make your life easy! Wasn’t that nice of them? :]

Run your app! You should now see a nice purple background as below:

Wow.

Well, the good news is you now know how to set the background color from code.

The bad news? That purple looks horrible! I didn’t think it could possibly get worse than that neon green ;]

UIColor has one more trick up its sleeve: aside from solid colors, it can take any image and convert it to a pattern that you can use in the background! If the image is smaller than the background, it will repeat or tile the image so it covers the entire view.

Perhaps that feature can save you from this purple haze? :]

Change the code for the background color in viewDidLoad to the following:

Rather than a specific color like green or purple, you’re calling colorWithPatternImage to get a pattern from an image. Images are stored as UIImage objects, so here you are setting up an UIImage with the “bg_tile.png” image, which will be the background for the app.

Run your app now — does it look any better?

Aww yeah — that looks a whole lot better! If you don’t see the nice background image, make sure the file name is spelled correctly in the code you changed above.

There are two more background images available for you to use in your app: one is for the timer label, and the other is for the score label.

Add these two lines to the viewDidLoad method, just after the line you added above which sets the view’s background:

The pattern is set in exactly the same manner, except the views use different images.

That’s it! Now run your project:

Whoa! This is problematic. The text was a little hard to read before — but now it is practically impossible to read!

If the background image is smaller than the view, UIColor will try to help you out by tiling, or repeating, the image; however, if the background image is too large, it will be cut off.

Just as you set the “Tap Me” button size right in the storyboard, you can do the same for the two labels. Open up MainStoryboard.storyboard and select the timer label. In the Size tab of the Utilities sidebar, set the Width to 133 and set the Height to 46, as such:

Now do the same thing for the score label. Select the score label, set the Width to 146, and then set the Height to 102, like so:

Excellent! Now run the app and have a look.

Well, it’s a little better, but the text is still really hard to read! Perhaps a lighter color would work better for the text on a dark background?

Open up Mainstoryboard.storyboard and select the timer label. In the Attributes tab, click on the black square next to Color to open up the color palette, as below:

In the color palette, select the Sliders tab and then select RGB Sliders from the pulldown menu. This will let you enter the red, green, and blue values for the label separately.

Set Red to 190, Green to 255 and Blue to 255, like this:

Note: After you set the color with the RGB sliders, the text might change to light blue or the entire label might turn into a light blue rectangle. Either result is okay! The color is being set and remember, the background image will be set from code in the viewDidLoad method.

Do the same set of steps for the score label. Select the score label, click on its color in the attributes to open up the color palette, and set the RGB slider Red to 190, Green to 255 and Blue to 255, like so:

Now run the project! Will this be it?

That looks great! Now not only have you made your first iOS app, but you’ve made a beautiful looking app! :]

Apps just aren’t about looks though — they need to sound great as well! To put the final polish on your app, you’ll be adding some music and sound effects in the next section.

Adding Sound

Music and sound effects are great ways to add character to your app. There are three sounds you’ll use in your app: background music, a beep 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! :]

iOS supports all kinds of features such as GPS, accelerometer, and sound playback. Each of these features is bundled into something called a framework. You’re already using a framework called UIKit, which includes views, view controllers, buttons, storyboards, etc.

To play sounds, there’s a framework called AVFoundaton that you’ll need to use. To add it to the project, click on the Tap Me project at the top of the file browser in the left sidebar, as below:

Then click Tap Me under targets, and select the Summary tab:

Scroll down until you find a section called Linked Frameworks and Libraries. This is a list of all the frameworks currently in your app. To add more frameworks, click the + (plus sign) button.

Whoa — that’s a lot of frameworks to choose from!

Find AVFoundation.framework in the list and select it. Then click the Add button, like this:

Awesome! Now the AVFoundation framework has been added to the project. You’re ready to get grooving with some sound! :]

The sound playback will be handled from the view controller code, so the first step is to set up the header file. Open up ViewController.h. Near the top of the file, you’ll notice this line:

Hey, look at that! There’s the import statement for the UIKit framework. Add another import statement for the AVFoundation framework so that the code looks like this:

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 as shown below:

That’s it for the header file! Time to get some sound playing. Open ViewController.m, and add this new helper method above the viewDidLoad method:

This method will return an AVAudioPlayer object, and takes two arguments: a file name and type. Let’s look at what it does section 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 something goes wrong, the audioPlayer will be set to nil, which you can check for with the exclamation mark symbol. If that happens, the error will be logged to the console.

5.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 just after setting up the background images:

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:

Run the project to test it out. You should hear a nice beep when you tap the button!

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:

Run the project again to test it out. You should hear a different beep as the number of seconds counts down. 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 this code to the bottom of setupGame:

You can adjust the volume of the background music so the beeps can still be heard. The setVolume method will take a number from 0 (off) to 1.0 (full volume); 0.3 is a good starting point for the background music.

Now run the project — and experience the glory of your fully featured app!

Feels good to be awesome, doesn’t it? :]

Final Thoughts

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.

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

From here, you might want to try some of the other tutorials on this site. We have a ton to choose from – whatever your interests may be.

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


上一篇:

下一篇: