Getting Started with WatchKit: Creating a Simple Guessing Game

Getting Started with WatchKit: Creating a Simple Guessing Game

Editor's note: As you know, Apple has included the WatchKit SDK in Xcode 6.2 beta, allowing developers to create apps for Apple Watch. You may have already started to try to develop apps with WatchKit. If you haven't started yet, this introductory tutorial is for you. This week, Julian from the Julo development team will introduce you to WatchKit and show you how to use it to create a simple guessing game. You will learn how to create a Watch app, layout the interface and test the app.

Let's start the tutorial now.

Apple first built WatchKit into Xcode 6.2 beta, which was released on November 18, 2014. This SDK allows developers to create apps for Apple Watch. To develop apps for Apple Watch, you first need an Apple developer paid account and download Xcode 6.2 beta. The sample app in this tutorial is written in Swift, which requires a certain level of Swift programming knowledge.

[[130330]]

Feature Film Begins

Understanding WatchKit Apps

Apple does not allow developers to create native Watch apps yet. Currently, the three Apple Watch user experiences you can build are WatchKit apps, Glances, and actionable notifications. This tutorial focuses on WatchKit apps and does not cover Glances and notifications.

First of all, the Watch app is not an independent application, which means that a paired app running on the user's iPhone is essential. The Watch app we are going to build is just an extension of the iPhone app, and the installation and management of the Watch app are the responsibility of the iPhone app. In addition, the iPhone app and the Watch app can communicate with each other, but this part is not covered in this tutorial.

Apple Watch has two screen sizes: 38mm and 42mm. However, you don’t need to design the user interface separately. Xcode will automatically adjust the layout to adapt to the screen size. However, it is not Auto Layout that is used here, but WatchKit’s unique layout system.

Sample App

Today we are going to create a simple guessing game for Apple Watch. The rules of the game are as follows: The Watch app will first determine a natural number between 0 and 5, let the player guess, and then detect whether the player guessed correctly and display the corresponding information. The App interface is as follows:

Creating the WatchKit Sample App

I assume you have already installed Xcode 6.2 beta 4 (or later). Please create a new project using the Single View Application template, name it WatchKitDemo (you can name it anything you want), select the language as Swift, leave other settings as they are, and save the project wherever you like.

As mentioned before, the Watch app is an extension of the iPhone app. To create a Watch app, select Editor > Add Target on the Xcode menu, then select Apple Watch > WatchKit App. Everything necessary to build a Watch app can be automatically generated using the WatchKit App template.

Uncheck Include Notification Scene, leave other options unchanged, click Finish, and a prompt will pop up asking whether to activate the new scheme.

Click Activate to add a new solution to your Xcode project, which can be used to test the app in the Apple Watch simulator. In the project navigator, you can see two new folders: WatchKit Extension and WatchKit App.

The WatchKit app only contains Storyboard and user interface related resources, while the code responsible for application logic and updating the interface is located in the WatchKit extension. In short, the Watch app provides views to display information and interact with users, while the iPhone app does the heavy lifting.

#p#

Designing the User Interface

Now we start designing the user interface of the Watch app. Select the Interface.Storyboard file under WatchKitDemo WatchKit App. Similar to iOS apps, Xcode provides Storyboard to design the user interface for the Watch app.

First, drag a text label into the interface controller. You will find that it is automatically positioned at the top of the view controller. This is because the Apple Watch screen is very small and the interface controller is divided into three areas: top, center, and bottom. Now select the text label and set the horizontal and vertical positions under the Position column in the Properties Inspector. Set both Horizontal and Vertical to Center.

Then change the text to "Your guess is: 3", as shown in the figure:

Next, we want to allow users to modify the guessed number. Drag a slider into the interface, and then modify the slider properties as shown in the figure:

Since the guess number is between 0 and 5, set the step size to 5, so that the slider is divided into 5 grids, each grid represents a number. We want 3 to be the default number, set the value to 0.6, the minimum to 0, and the maximum to 1.

After the settings are completed, drag a button from the object library, set the title to Guess, and set the vertical position to Center.

To build a complete interface, we also need a text label to show whether the user's guess is correct. Drag a Label into the view, set the text to "Press Guess to play", then change the vertical position to Bottom and set the font's Min Scale to 0.5 to allow the text to fit in a narrower space. The final design is as follows:

Code Time

OK, after setting up the interface, let's start writing code. As mentioned before, the program logic is in the WatchKit Extension. InterfaceController.swift has been associated with the Interface Controller just designed.

Open the source code file, create outlets for the text label and slider, and then add the following code to the InterfaceController class:

  1. @IBOutlet var guessSlider: WKInterfaceSlider! // the slider  
  2. @IBOutlet var guessLabel: WKInterfaceLabel! // the label displaying the guess number  
  3. @IBOutlet var resultLabel: WKInterfaceLabel! // Wrong/Correct Label  

Then comes this line of code, which creates a variable for the guessed number:

  1. var guessNumber = 3

Now that the project infrastructure is created, it’s time to connect the interface elements to the corresponding outlets. Switch back to Interface.storyboard, open the assistant editor, display the code file you were just writing, and connect the outlets to the corresponding controls.

Now control-drag from the slider to the code. This time, instead of IBOutlet, select IBAction and name it updateGuess.


The following functions will be automatically added:

  1. @IBAction func updateGuess(value: Float) { }

This method will be used to obtain the number guessed by the user and update the text prompt. Insert these two lines of code into it:

  1. guessNumber = Int(value * 5)
  2. guessLabel.setText( "Your guess: \(guessNumber)" )

Since the slider value range was previously set to 0 to 1, the value multiplied by 5 is the number we actually need, and then the text label is updated.

Hold down control and drag from the button to the code, and then create an action method named startGuess. This method generates a random number, compares it with the guess number, and updates the prompt content. The code is as follows:

  1. @IBAction func startGuess() {
  2.      var randomNumber = Int(arc4random_uniform(6))
  3.        
  4.      if (guessNumber == randomNumber) {
  5. resultLabel.setText( "Correct. You win!" )
  6. } else {
  7. resultLabel.setText( "Wrong. The number is \(randomNumber)" )
  8. }
  9. }

The code first uses the arc4random_uniform(6) function to generate a random number between 0 and 5, then performs a comparison and displays the result.

Done. Now you can test the app.

Run the Watch App

To run the app, select the "WatchKitDemo WatchKit App" solution, specify the device to run on, and click the Run button to test the app. You can also switch the screen size in the simulator by going to Hardware > External Displays > Apple Watch - 38mm.

Pretty good, right? How does it feel to get started with WatchKit? You can download the project files here for reference.

Original author: julian engel   Translator: @TurtleFromMars

Original text: WatchKit Introduction: Building a Simple Guess Game

<<:  XY Apple Assistant: Recommended must-have gadgets for spring outings

>>:  Yelp iPhone client redesign: Problems and thought process

Recommend

Xiaomi's marketing crisis was cleverly resolved by Alibaba

With the full explosion of social traffic in 2016...

Marine mammals harbor seal

When it comes to harbor seals, do you naturally t...

How can we-media write explosive articles? Use these 5 steps!

What should a complete advertising copy contain? ...

Detailed explanation of Tik Tok information flow delivery strategy!

Nowadays, more and more companies and projects ar...

Quick quiz: Are you right-brained or left-brained?

© Atlassian Leviathan Press: The "two-mind h...

Do you know these Winter Olympics venues?

Nickname: Ice Ribbon Venue name: National Speed ​...

Apple announces the official launch of App Light Code

Apple announced to developers yesterday that it h...

How to plan an excellent Christmas recruitment event?

As December is coming to an end, Christmas is aro...