User Tools

Site Tools


android-labs-s16:ios_tutorial

Week 1- Introduction and Views

This content was taken from Spring 2014, Tutorial 1

This is the first section of the iOS crash course. These three lectures will cover the basics of the development process. By the end of the third you should have a solid foundation to begin iOS development yourself. However, this is only a brief primer! In the rest of the iOS lectures we will be diving into more difficult and complex topics in a more comprehensive way. For theses three lectures, the whole picture will not be clear; follow along closely and try to understand each step.

Lecture 1 will cover:

  • The programming environment
  • Xcode
  • HelloWorld
  • UWMadInstagram

In these three lectures you will be making a sample application called “UWMadInstagram.” This app will use UW Madison's Instagram feed, providing users with an interface to view images and comments. This app will be pretty unimpressive in its functionality, but it will show you how to complete a lot of basic tasks.

You may notice as you make progress through the tutorial that your IDE colors do not match those from the screenshots. That's my fault: I can't stand a white background on my IDE's, so my Xcode color scheme is set to “Dusk.” If you'd like to change yours to match, instructions are included below.

Changing IDE Colors

  1. Go to Xcode > Preferences > Colors
  2. Select “Dusk”

Development Environment

Xcode is the IDE used for all iOS development. Although 3rd party IDE's exist, you should learn and appreciate Xcode, its fast, slick, and optimized for iOS. Because Apple has vertical control over their products (i.e. they have control over their products from hardware to operating system to application) Xcode can make a lot of menial tasks very easy and integrates well into the development cycle.

Creating a New Project

  1. Open the program to begin. We will start by creating a new project through File > New
  2. Enter a name for your new project. Make sure “iPhone” is selected under the “Devices” dropdown. Enter a name for the Company Identifier (contents don't matter right now)
  3. The next panel provides some preconfigurations for your new project. Don't worry about them for now– make sure the highlighted options are selected

Xcode Interface

Xcode's main view may seem a little overwhelming right now, but a lot of the options are not needed at this point. The two circles on the image below show everything you need to pay attention to now. On the top left you'll see a play button. This runs your application in the Simulator. Top right contains six buttons. The three on the left represent panes currently open in Xcode. The three buttons on the right allow you to change editor types. Don't worry too much about them now!

Click on the Main.Storyboard file in the project navigator in the left pane so your screen looks like the screenshot below. This is a storyboard, which lays out the interface of your application.

Run your application to make sure everything works. If the simulator does not start you get an error, go back to the iOS home page and follow the instructions under the Lab Simulator Fix section.

InterfaceBuilder

InterfaceBuilder (commonly abbreviated as IB) is Xcode's integrated interface-building tool. It is a WYSIWYG (what-you-see-is-what-you-get) editor that allows you to drag and drop Views onto the screen easily. One of the nicest features of Xcode, InterfaceBuilder allows you to deal with the View creation process without ever having to write a single line of code. The file that InterfaceBuilder operates on is called the storyboard.

IB can look a little complicated, but there are only a two broad kinds of items that appear on the screen.

  1. View Controllers- every long rectangle on the screen represents a ViewController. These rectangles are the only things that can “float” in IB's main window
  2. and 3. Arrows- arrows in IB represent relationships between ViewControllers. The arrow on the left of the image above identifies the first ViewController to appear when the app launches. Arrows between ViewControllers are called segues and represent a transition between ViewControllers

That's all fine and dandy, but you haven't actually learned what Views and Controllers actually are. One of the ways in which iOS is structured is called MVC, which stands for Model, View, Controller. This is just a way of thinking of different objects in code and keeping them separate.

  • Views are interface items that interact directly with the user by displaying data or receiving button clicks.
  • Controllers are each responsible for a different “scene” in the app, each which serves a particular function. A Settings scene , a Home scene , and a Contact scene each have different controllers. Controllers own views, and each gets their own setup of them in InterfaceBuilder. They also, obviously, control.

The following are examples of views in the pictures below

  1. Button
  2. Image
  3. Table

The following are examples of view controllers in the pictures below

  1. Settings
  2. General
  3. Autolock

7.jpg


Hello, World!

Its useful to do a quick Hello, World starter just to get your feet wet. We will code two variations to get an idea how InterfaceBuilder works.

Click on the ViewController.m file on the project navigator. Type the following line before the closing brace in the viewDidLoad method.

NSLog(@"Hello, World!");

Run your program by clicking the play button in the top left corner. Check the console for your message!

Ok, that was pretty basic. NSLog is a library function call that logs the message within the quotes to the console. The @ sign before the quotes means string literal. Don't worry about it now, just understand that whatever is in between the quotes gets pushed to the console.

In this next step, we're going to make a Hello, World button and label on the main interface.

Adding Views to the Root View Controller

  1. Select the Main.storyboard file in the project navigator
  2. Ensure the Object Library is selected in the bottom right of the screen (circled)
  3. Scroll through the list of objects to find a Label, or type “label” in the search box on the bottom right corner
  4. Double-click on the view controller on the storyboard to ensure it is in focus. Drag the label onto the top of the view controller
  5. Repeat the last two steps with a Button, placing it below the label

This is what your view controller should look like after the last steps. We have two minor changes to make to the format and then you will hook up the views you just added to code.

Formatting Views

  1. Change the title of the button to “Greeting.” To change the title of the button, double-click on it and type in the new title.
  2. Change the width of the label to accommodate our greeting. Click on the label and resize it using the draggable sides. Make it slightly smaller than the width of the controller.

At this point you can run your app again and see the views laid out on the root view. Unfortunately, since the views are not connected to code, they don't do anything terribly interesting.

What does this mean? Remember, MVC splits objects into different types, keeping their code and interaction seperate. Each type of object's source code shouldn't ever mix with other types of object source code. Views don't merge into controllers and vis-versa. You have already seen Views (the label and the button) and Controllers (the rectangle in the middle of the screen, and the file you wrote “Hello, World!” in.) Controllers are the masters of the program, so to make Views do anything interesting we have to connect the two. We will discuss MVC in more detail in the next lectures.

We connect Views to Controllers using a simple drag and drop. There are two kinds of connections you can make:

  • IBOutlet- gives the owning view controller a reference to the view. It can change the content, properties, and functionality. This is used for non-interactive views that need to be changed dynamically.
  • IBAction- establishes a callback from a view to a view controller. When some action happens, the view calls a method in the controller. This is used for responsive functionality.

IB stands for InterfaceBuilder. It is an established convention in iOS to prefix your objects with 2 letters that tell the programmer from what library they come from.

When the user presses the button, we want to change the text of the label to “Welcome to UW Madison Instagram!” In order to do this, we need access to the label through an IBOutlet, and we need to know when the button is pressed through an IBAction. In order to make connections, we have to use the Assistant Editor to see the storyboard and the code.

Opening Assistant Editor

  1. To open the assistant editor, press the second button from the left in the top right corner. The icon looks like a tuxedo.
  2. There is a bug in the most recent version of Xcode. All connections are made to .h files, but the editor always opens the .m file. To switch files, click on ViewController.m and find ViewController.h
  3. Finally, we want to encapsulate our connections so they don't spill all over the place, making everything confusing. To do that, you must add curly braces, {}, after
@interface ViewController : UIViewController 

but before

@end

Anything inside of the braces is private to our class.

Creating Connections

  1. Create an outlet from the view to the controller by right clicking on the label, dragging to the right, and releasing inside of the braces. A small notice will appear when you are in the right section.
  2. Name the label labelHello and click Connect in the popup that appears
  3. Create an action from the button to the controller. This time, when right-click dragging, make sure you drag outside of the curly braces.
  4. Ensure the Connection field reads Action, not Outlet. Name the action buttonHello.

This is what ViewController.h should look like when you are finished.

Ok. That was a lot of unexplained steps in quick succession. If this seems painful, don't worry. Its really quite simple, and at this point you've performed all the steps you'll ever need to build almost any iOS interface! If you can't quite understand what just happened, don't worry. You can just repeat the previous steps over and over to build your interfaces, and eventually things will click. We will discuss a little more of the theory of InterfaceBuilder in later classes.

There's one more step left in our greeting. If you click on the ViewController.m file in the project navigator, you'll see a new method was added that matches the name of the action you just created. Every time the button is pressed, this method will get called (and thats why its called a callback.)

When the button is pressed, we want to change the text of the label. The method used to do this is called setText: Don't worry about the syntax right now.

React to buttonHello Callback

  1. Place the following method in between the braces of the buttonHello method
[labelHello setText:@"Welcome to UW Madison Instagram!"];

Run your program and check the button and greeting. If the text is being cut off, your label isn't wide enough.


UWMadInstagram

This app will serve a few, fairly limited functions. Users will be able to connect to UW Madison's Instagram feed over the internet and display all of the images and comments listed there.

Here, you will begin creating the interface of the application though InterfaceBuilder. First, each scene of the app will get a ViewController. Then, you will drag Views onto their corresponding ViewControllers.

The view objects that you drag onto ViewControllers in InterfaceBuilder make up the “scene” for each view controller. When that ViewController is loaded in your app it loads all of the views you dragged onto it in InterfaceBuilder. We won't be coding ViewControllers in this lecture.

Our app will have 4 screens

  1. Home- this is the controller you already have on the screen. Users will use this as springboard to access the rest of the app. This will be the first controller to appear. Contains two buttons that transition to Settings and Posts.
  2. Settings- users can set the number of posts to display in the Posts controller here.
  3. Posts- display a list of each user and each comment for all the instagram pictures within a scrollable table. When a user touches an entry, transition to the Images controller.
  4. Images- display the Instagram image and the comment below it.

Adding View Controllers to App

  1. Make sure the storyboard is selected
  2. Scroll through the object library (or search using the text box) to find a View Controller
  3. Drag it onto the storyboard next to the original View Controller
  4. Repeat until your storyboard matches the image below

Now we're going to populate the views of the app. The process for dragging and dropping views onto controllers is simple, the only thing that changes is the type of view. After you're finished, do not connect IBActions or IBOutlets.

Adding Views to View Controllers

Check the image below for a final layout of what the app's views look like. The views used are:

  1. Buttons
  2. Label
  3. Text Field
  4. Table View (not a Table View Controller)
  5. Image View
  6. Text View

You should size the views as shown in the picture, and change the names of the two buttons on the first controller and the label (tagged with a 2 in the image) to match. Note: the names under the ViewControllers do not match what yours will look like, and the original view controller does not have the greetings button listed.)

Congratulations, you've just built an interface. There is one small thing missing, the ability to transition between view controllers. The switch between view controllers is called a segue (pronounced seg-way.)

The Images button should connect to the view controller where you put the Table View. The Settings button should connect to the controller that has the Text View and the “Images per Page” label.

Creating Segues Between Controllers

  1. Right click on a button on the original view controller and drag onto the desired view controller
  2. Select push from the popup menu that appears
  3. Repeat for the other button

Now, if you test the app again, pushing the Images and Settings buttons should switch you to a new view controller. There's no way to get back, unfortunately, which brings us to the most commonly used tool for organizing Controllers, the Navigation Controller.

A UINavigationController is a meta-controller (it controls other controllers) and you will use it all the time to keep your controllers in order. Its function is very simple: it maintains a stack of view controllers, which creates a controller hierarchy. All this means is there are controllers below the active controller, and new controllers can be pushed onto the active controller. When this push happens, a new controller becomes the active controller.

The navigation controller automatically adds a back button after a segue happens to show that there is another controller below the active one. When this back button is pressed, it informs the navigation controller that a pop happens, which removes the active view controller from the screen and exposes the one below it.

Adding a Navigation Controller

  1. Fine a Navigation Controller in the object library and drag it onto the storyboard
  2. The navigation controller is the controller on the left. The one on the right is a stock Root View Controller, but we want to use our own view controller. Click on the right one and delete it (hit delete key)
  3. To set up our home view controller as the root view, right click drag from the navigation controller to the original view controller and select root view from the popup that appears.

There's one small change we still have to make to let the app know that we want the Navigation Controller to be the root view controller. The arrow that doesn't have a left end denotes the root view controller, you need to drag it from the original view controller to the navigation controller.

Change the Root View Controller

  1. Drag the arrow from the greeting view controller to the navigation controller

Test your app. You should be able to move back and forth between the three view controllers (the menu, the table, and the settings.)

Conclusion

If this seemed a little slow, don't worry. The fun is just starting. Covering iOS development is a little weird for most people at first, because they have to deal with a new language, IDE, and set of conventions like MVC. In the next lecture you'll learn the basics of the Objective-C language and start making custom View Controllers to give your app some functionality.

This first set of lectures is introductory. Its meant to get your feet wet and hopefully give you a sense of what the process of creating an app entails. It will not train you to be a successful developer! If you choose to stay with iOS we'll dive into the theory, giving all of the new terms learned here a place in the big picture. Don't worry if it seems like you're following steps here without understanding, doing is one of the best ways of learning!

Graphic Grant Tracker

Taken from Sprint 2014– Tutorial 4 This is an iOS tutorial on creating the Graphic Grant Tracker, an iOS app made to track grants in the CS department.

Steps described in this tutorial will not necessarily hold your hand. To review introductory iOS material, please read the iOS Crash Course or check the Building Blocks pages. This tutorial has had instructions and screenshots trimmed from it to make it more difficult; copying and pasting code to get through it doesn't help you at all.

App Motivation

Any professor working in the CS department usually has to juggle dozens of spreadsheets, each which individually track a grant, when performing research. These spreadsheets consist of a series of accounting entries into and out of the account. GGT aims to provide a simple, remote interface for viewing all of this data cleanly and quickly.

Users of the app place all of their spreadsheets in a private directory on the CS network and then run a Ruby script which encrypts them, places them in the user's public directory, and builds the PHP serving script/API. This script is visible at an external URL– the iOS app goes to this URL and transacts with the “server,” receiving a CSV (comma seperated value) of each spreadsheet in JSON (java-script object notation) format. Although there are many features built into the API, for the purposes of this tutorial we will approach its functionality incrementally.

The app parses each spreadsheet, graphs the aggregate totals of interesting accounts, and provides a simple interface for analyzing the data.

Debugging Crashes

All crashes will print you an exception and stacktrace to the console, but these are rarely enlightening. Thankfully, Xcode allows you to set a breakpoint at the point of an exception. This jumps to the offending line 90% of the time, showing you exactly what went wrong.

Setting and Exception Breakpoint

  1. Click the exception panel on the left side (see screenshot)
  2. Click the plus sign in the absolute bottom left of the corner
  3. Select “Add Exception Breakpoint”

Introduction and Setup

Instead of creating the whole interface in one go like the Crash Course, we will incrementally build parts of it each lecture in order to introduce new elements as well as pounding the information through with repetition. Three new concepts will accompany this repetition: custom table cells, persistent device storage, and intermediate API calls (you'll also see your first blocks).

Understand that the finished product represents minimum 60 hours of work. Having you write the whole thing in three lectures would be sadistic, so you will be importing utility classes, models, and the graphing library in order to save time. You will still have to implement almost all of the controller logic.

Any instructions that you've covered twice will be sparse. Look back at your old code, at the old tutorials, or on google!

Create a New Project

  1. Create a new project with a single view. Give it a name.

Setup a Nav Stack with a Root ViewController

  1. Delete existing controller on Storyboard
  2. Add a Navigation Controller, delete its root view controller
  3. Add a new, plain UIViewController and set it as the Nav's root

Create and Set Subclass

  1. Create a new ViewController subclass called RootViewController
  2. Subclass the controller in InterfaceBuilder
  3. Set the title of the new controller to “Grants”

See? Sparse.


Table

Back to our best friend, the Table. For a review on the purpose, structure, and manipulation of views please check the Crash Course.

In the spirit of UX-centric design, we want the user to immediately be presented with his or her grants upon opening the app. RootViewController will display settings and transition buttons on a bar on top of the screen and all grants are listed in the table.

Everything in this section will be similar to the content covered in the Crash Course with one exceptions. Remember you can subclass any view or controller to realize custom behavior. Just like you can subclass UIViewControllers and customize their views to be unique from other controllers, in order to get custom table cells we'll have to roll our own UITableViewCell subclass. This is an important part of using tables, since you will generally want to customize the appearance of your cells.

Add UITableView

  1. Add a table to the RootViewController, resize to fill controller
  2. Connect delegate and data source properties using the controller shortcut as shown below
  3. Create an IBOutlet to RootViewController named “tableGrants”

The table with the new cell added (next step)

The process for adding a UITableViewCell is the same as adding any other view: simply drag, drop, and customize. To “Layout” an object in iOS development means to add and edit views within the object to set up its overall interface.

Layout Custom UITableViewCell

  1. Drag a Table View Cell from the object list onto the table
  2. Layout the cells contents as shown below
  3. Select the “Grant” and “End Date” labels and change their fonts to bold from the pane on the right side of the screen, using the attributes inspector
  4. Downsize the font size of the [totals] label

Just like sub-classing a controller, you must create a new class, with .h and .m files, that will be instantiated to handle the functionality of your new cell by connecting outlets.

Subclass UITableViewCell

  1. Create a new object named “GrantCell,” ensure it subclasses UITableViewCell
  2. Select the cell in storyboard and set the subclass
  3. Return to the Identity Inspector and set the Identifier field to “cell”
  4. Connect “Name of Grant,” “End Date,” and “… remaining” to the header file as public outlets, named labelName, labelEndDate, and labelRemaining respectively
  5. Set the cell's reuse identifier to “cell”

Note that selecting the cell and opening the assistant editor will not pull up the correct source code file. Assistant editor tries to open whichever file complements the current selection on the main pane, but since the GrantCell is contained within the RootViewController, the Assistant picks the controller. You'll have to manually select the appropriate header file by clicking Automatic on top of the Assistant Editor, changing it to Manual, and drilling through your project files for the right one.

When establishing the IBOutlets, do not create braces in the header file! Place them between @interface and @end without braces.

If you're here in this class now, you've elected to work on an iOS project this semester and may have some interest working on future development. Its then safe to assume you'll have to use a table at some point again, ergo you'll have to complete this next step without hand-holding. Remember: Don't Repeat Yourself. These methods should be copy-pasted from old projects or the internet every time, not written from scratch.

Implement Delegate Methods

  1. Find the four UITableView delegate methods. Copy them into RootViewController

You'll undoubtedly have to edit the delegate methods to get the project to compile. After you've figured it out, run your app and ensure you see the dummy values in the cell

android-labs-s16/ios_tutorial.txt · Last modified: 2016/01/25 19:32 by mbarboi