User Tools

Site Tools



This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
android-labs-s16:ios_tutorial_2 [2016/01/25 20:15]
mbarboi created
android-labs-s16:ios_tutorial_2 [2016/02/05 15:32] (current)
xuan [CocoaPod]
Line 1: Line 1:
 ====== Introduction ====== ====== Introduction ======
-// Taken from Spring 14 Lecture 2 //  
 This is part 2 of the iOS Crash Course. This is part 2 of the iOS Crash Course.
Line 7: Line 5:
 In this section, we will go over the following topics: In this section, we will go over the following topics:
   *Miscellaneous Fixes and Tips   *Miscellaneous Fixes and Tips
-  *Objective-C Introduction +  *Segues
-  *Subclassing View Controllers+
   *Tables   *Tables
-By the end of this tutorial you should have an app one step closer to "​functional."​ As this is the first lecture that introduces Objective-C,​ however, expect to take a little bit more time deciphering it. Code has been provided for you to cut and paste in the first few examples, but by the end you'll have to write a few lines of it yourself. ​ 
 First, a few miscellaneous tweaks. First, a few miscellaneous tweaks.
-===== Git ===== 
 In the first lecture of the crash course you should have made a basic interface for the sample Instagram app. Since following lectures will build upon this content it would be nice if your code perfectly matches the sample code. In the first lecture of the crash course you should have made a basic interface for the sample Instagram app. Since following lectures will build upon this content it would be nice if your code perfectly matches the sample code.
-The app has been checkpointed at a finished state after lecture 1 and uploaded to GitHub as a repository. You should clone this repository for lecture 2. If you have never used GitHub or even Git, read about it [[http://​​~cduan/​technical/​git/​|here (conceptual overview)]] when you have spare time. [[http://​​questions/​315911/​git-for-beginners-the-definitive-practical-guide|This guide details Git's usage from a practical standpoint.]]+=====Git===== 
 +If you have never used GitHub or even Git, read about it [[http://​​~cduan/​technical/​git/​|here (conceptual overview)]] when you have spare time. [[http://​​questions/​315911/​git-for-beginners-the-definitive-practical-guide|This guide details Git's usage from a practical standpoint.]]
 Essentially Git and other revision control/​source code management tools allow you tremendous power when working on individual projects or collaborating with others. It protects you from mistakes, allows multiple people to work on the same project safely, and gives developers the ability to track their progress. Essentially Git and other revision control/​source code management tools allow you tremendous power when working on individual projects or collaborating with others. It protects you from mistakes, allows multiple people to work on the same project safely, and gives developers the ability to track their progress.
-===Cloning Lecture 1 Project=== +The first thing you should do is to start with registering an account of Github : https://​
-  -Open Xcode +
-  -Click on Source Control > Check Out  +
-  -Enter the following URL for "​Repository Location"​-- ​https://​​damouse/​cs407_UWMadisonInstagram.git +
-  -Save the project  +
-  -Open the project.+
-{{ ios-labs-s14:​2_34.png }} +After registration,​ start with creating an new repository, for public repository, its free, but anyone can see your code.
-{{ ios-labs-s14:​2_32.png }} +
-{{ ios-labs-s14:​2_33.png }}+
-===== Miscellaneous ===== +{{:​android-labs-s16:​w2-1.png}}
-The following instructions address a few lapses from the first lecture. All of these steps are optional+
-You never learned how to use the debugger or how to diagnose crashesso quick overview of a crash is shown. ​+Now after you create your new repositoryhere’s ​example **https** link to your git
-Finally, you may have noticed some clipping between your storyboard setup and the simulatorStoryboard shows 4 inch view controllers (iPhone 5 and later), but the standard simulator is the 3.5 inch version (pre iPhone 5). Storyboard is absolutely deterministic;​ if you'd like to fix the clipping you'll have to switch the simulator.+**https://​​xuaninbox/​CS407.git**
-=== Debugging ==== +So you have two ways to link your git with your projectwith command line or with GUI interface.
-  -Active Threads +
-  -The second button from the right toggles the bottom debugging pane +
-  -The Console. Upon crashing, the device will print the reason for the crash as well as a stack dump. Scroll up until you see "​Terminating app due to uncaught exception...."​ This is the reason ​your app crashed. +
-  -A visual object inspectorallowing you to look through all variables in memory +
-  -Hit the folder button to get back to the project navigator +
-{{ios-labs-s14:​2_16.png }}+
-===Changing Simulator Size=== +here’s how you can do it with GUI in Xcode
-  -To the right of the Play button in the top left corner is the name of your application. To the right of that is a blue icon with the name of the active simulator. +
-  -Click this, select "​iPhone Retina (4-inch)"​ +
-{{ ios-labs-s14:​2_0.png }}+
-===Dealing with an Unresponsive InterfaceBuilder=== +{{:android-labs-s16:w2-2.png}}
-Have you tried dragging a view onto a controller only to have it snap back to the menu? InterfaceBuilder will only allow you to drag views onto controllers that it thinks are "in focus."​ If you can't drag a view in, double click on the controller to zoom in, or use the zoom buttons on the bottom right of the storyboard. +
-====== Objective-C ====== +
-Formally, Objectve-c is a strict object-orientated superset of C. This means is that Objective-C shares largely the same syntax and conventions as C but with an objective-orientated rather than procedural focus. It is used to create both iOS and OSX apps, and was developed by NeXT in the 80s; NeXT was purchased by Apple and while the language is not technically proprietary,​ it is almost exclusively used for Apple applications.+
-The language takes a little getting used to. If you've coded in C before ​the transition to Objective-C will be little easier. Even if you have no experience in C, however, the learning curve is abrupt, but short. It takes a week or two to become comfortable. ​+switch ​to the **remote** tab and **add remote**
-====Similarities to C==== +{{:​android-labs-s16:​w2-3.png}}
-The easiest way to describe the language is to compare it to CAgain, if you have not programmed in C before this may be a tougher pill to swallow; everything you need to know is still mentioned, don't worry!+
-===Headers and Implementation Files=== +again in the **Source control****click commit**
-Objective C makes use of header and implementation files (.h and .m respectively). The header file is where the interface of a class is defined and includes publicly visible variablesmethods and import statements. The implementation file is where the implementation of those methods go, where private methods live, and is where the majority of code lives.+
-An sample empty, auto-generated header file. +{{:android-labs-s16:w2-4.png}}
-{{ ios-labs-s14:2_23.png }} +
-  +
-An sample empty, auto-generated implementation file. +
-{{ ios-labs-s14:​2_24.png }}+
-====Objective-C Syntax==== +**Message** ​is required and when select **Push to remote**, it will also push it to the remote git
-Two things differentiate Objective-C from other languages you may be familiar with. The first is obvious: this language has different syntax than others. The second ​is a little less subtle: conventions drastically alter the appearance of the code.+
-===Convention- Uncomfortable Verbosity=== +//Now go back to ur git and see if ur code is there//
-You've probably noticed by now that methods in objective-c are lengthy. This is a convention. All names in Objective-C should be as long and painfully verbose as needed ​to describe the function or variable.  +
-{{ ios-labs-s14:​2_35.png }}+
-Why do this? Simply, so that code can be read aloud in a logical way. Method arguments are inter-spaced with the method names, by having long method names and variables, you can read along the line and clearly see whats happening.+=====CocoaPod=====
-So keep your mtri_sk_main and dCV() and strerror in your other languages, here everything should be spelled out in camel case. If this seems too painful ​to do, and it should, don't worry. Xcode'​s autocomplete is the only reason this works as a method of coding; it does 90% of the coding for you.+CocoaPod is a easy way for u to manage ​the libraries ​of your project, now start with the tutorial to install cocoapod on https://​
-===Convention- 2-letter Prefixes=== +after you finish the INSTALL section
-All variables used officially in Objective-C are prefixed with two letters that inform the developer which framework they come from. You don't have to prefix your variables UNLESS ​you provide your code to other people to use. +
-{{ ios-labs-s14:​2_35.png }} +use command line to go to ur project folder
-The method above uses items and methods from a library called RestKit. The prefix is "​RK."​+
-===Syntax- Class Declarations=== +and do **pod init**
-{{ ios-labs-s14:​2_30.jpg }}+
-===Syntax- Class Instatiation=== +open the **Podfile** in the folder
-{{ ios-labs-s14:​2_22.png }} +
-When declaring an object, Objective-c uses two phrases: "​alloc,"​ and "​init"​+
-  +add the following text
-  -Alloc-Allocates space in memory +
-  -init-Calls ​the constructor+
-You may have noticed by now Objective-c uses pointers. if you don't know pointers, don't worry about it nowjust emulate the syntax written here.+    target ​'P2' do 
 +    pod '​AFBlurSegue', ​'~> 1.2.1' 
 +    end
-===Syntax- Method Declarations=== +after **pod install** or **pod update** go to you project, from now on you **should use XXX.xcworkspace**
-{{ ios-labs-s14:​2_30.jpg }} +
-{{ ios-labs-s14:​2_31.jpg }}+
-===Syntax- Messaging/​Method Calls=== +OSX 10.11 BUG?
-{{ ios-labs-s14:​2_22.png }} +
- +
-  -Method type - a "​+"​ means this is a class methodLikewise a "-" denotes an instance method +http://​​questions/​32810808/​can-not-perform-pod-install-under-el-capitan-15a279b
-  ​-Return type In this instance the return type is void +
-  ​-Method Signature Keywords ​the separate parts of the method name InsertObject:​atIndex. Unlike most of java the method is treated like separate blocks +
-  ​-Argument types Parameter types that the method are asking for. In this case "​id"​ and "​NSUInteger"  ​- +
-  -Parameter names -Just the names of the objects you are feeding the method: an id named anObject and an NSUInteger named Index+
-Nothing too difficult here. Notice how the method declaration reads almost like a coherent sentence"​Insert object anObject at index index."+{{:​android-labs-s16:w2-5.png}}
 +Awesome! You just installed you first 3rd party library: AFBlurSegue ​
-In java and many other languges, the most commonly used notation for method calls is the dot notation. For example:+https://​​AlvaroFranco/​AFBlurSegue
-  object.doSomething(Stuff,​ moreStuff);+=====Segue=====
-Objective-C is different in that **no methods are ever called.** Instead, objects exchange //​messages.//​ For all intents ​and purposes, this is a semantic difference, and you can consider methods being called as they are in every other language. ​+In this section you will create the two basic segue, ​**Show** and **Present modally** ​
-  [object doSomethingwith:​stuff andThen:​moreStuff];​+Now use 3 View controller
-In this example, the method called "​doSomethingWith:andThen:" is called on the object called "​object."​ "​stuff"​ and "​moreStuff"​ are arguments passed into the method.+{{:android-labs-s16:w2-6.png}}
-Essentually,​ the usual "(" is replaced with ":" ​to signify arguments, and methods with more than one parameter generally split the method call nameThe general form for a multi-parameter method call usually looks like this:+The **two button ​(show & present modally)** will let you **either show or present modally** ​to the new controllers.
-  [object methodPart1 :parameter1 methodPart2 :​parameter2];​+Also by using
-Look back at the picture of the insertObject:atIndex method. The code to call this method is  +    override func prepareForSegue(segueUIStoryboardSegue,​ senderAnyObject!) ​ 
-  [array insertObject:object atIndex:​int]  +    if (segue.identifier == "​XX"​) ​
-  ​ +
-where array is the object'​s name.+
-{{ ios-labs-s14:​2_29.png }} 
-Properties private instance variables with auto-generated getters and setters. ​ 
-  -weak/​strong- hold onto the variable strongly in case of "​garbage collecting," ​or do not  +You should make the label on the new controllers to print ‘SHOW’ ​or ‘MODAL’
-  -nonatomic- do not create locks for this variable +
-  +
-Example of property usage in a header file. +
-====Commonly Used Data Structures====+
-Most of the data structures in Objective-C are pretty much similar to their counterparts in other languages+Now try run it in the simulator and see if it works!
-===NSArray=== +=====lifecycle=====
-{{ ios-labs-s14:​2_22.png }} +
-NSArray class and example implementation.+
-{{ ios-labs-s14:​2_26.png }}  
-An example usage of an NSString. 
-===NSDictionary=== +This should be a easy one! lets try to understand how the view controller works, try to do the following
-{{ ios-labs-s14:​2_25.png }}+
-Storage object that sorts items based on a "​key"​. Calling with the key returns the data at that key location.+{{:​android-labs-s16:​w2-7.png}}
-If you ever find yourself stumped about anything data structure related, Apple has some excellent documentation at https://​​library/​mac/​navigation/​ . StackOverflow should be your first stop for any other issues.+Now try run it in the simulator and tell us what is the sequence of the print and why so.
-====== ​UI Touches ​====== +=====Delegate=====
-Before we dive into the code for today'​s lecture, there are a few more touches we have to add to the interface of the app, specifically the table. UITableViews are incredibly common, and can be found in almost any app on the App Store. Their purpose is to display a set of data; because they have to deal with almost any kind of data and they are used so often, there are a few details that have to be taken care of to customize their use. +
-First, we'll have to add a static UITableviewCell to get a visual representation ​of the cells we'll use. Dynamic cells are not shown in the storyboard and are spawned at runtime. Strictly speakingthere is no need to make static cell in this apphowever creating static cells allows us to view them in InterfaceBuilderwhich is key to later customizing them+Delegate is one of the most important aspect of the iOS programminglets start with simple delegate**UITextFieldDelegate**this delegate ​is used to handle text **UITextField**.
-Then, we'll connect that cell to the last view controller that doesn'​t ​have a segue. The steps are the same as before, right-click ​and drag to the view controller.+Lets say you have a UITextField on your ViewController ​and you want to be notified every time user start to type something in it.
-Finallywe'​ll ​set titles on all of the view controllers.+**first drag the UITextField onto any of the ViewControllers you have created**and **set the component’s delegate as its ViewController**
-This will be the first experience with the right pane of Xcode, which allows us to customize properties of views, controllers,​ and files through a simple GUI.+{{:​android-labs-s16:​w2-8.png}}
-===Adding Static Table Cells=== +**Add the delegate ​in your swift code and the function that handle ​the callback**
-  -Make sure the table is selected ​in the storyboard. Click on the icon for the //​Attributes Inspector,//​ it looks like a badge (circled in screenshot below) +
-  -Set the //Content// field circled below from "​Dynamic Prototypes"​ to "​Static Cells."​ +
-{{ ios-labs-s14:​2_3.png }} +
-{{ ios-labs-s14:​2_4.png }}+
-You should see blank cells appear within the table. You **could** now customize them by dragging and dropping views onto them like we did with the controllers,​ but that is out of the scope of this tutorial+{{:​android-labs-s16:​w2-9.png}}
-===Creating a Table Segue=== +As you can see we have added **UITextFieldDelegate** ​and a function **textFieldDidBeginEditing**
-  -Click on the first cell in the table +
-  -Right-click on it and drag it to the Posts controller, directly to the right +
-  -Select "​push"​ from the popup +
-{{ ios-labs-s14:​2_5.png }}+
-Remember that a //push// segue relies on a UINavigationController to maintain ​the stack of ViewControllers that make up your app+//Now try run it in the simulator and see what happened when you start typing into the textfield.//
-===Changing View Controller Titles=== +===Cloning Lecture 1 Project=== 
-  -Ensure the original, greeting view controller is selected +  -Open Xcode 
-  -Double-click in the middle of the top, grey bar +  -Click on Source Control > Check Out  
-  -Enter "UWMadisonInstagram" +  -Enter ​the following URL for "Repository Location"​-- ​​damouse/​cs407_UWMadisonInstagram.git 
-{{ ios-labs-s14:2_2.png }} +  -Save the project  
-{{ ios-labs-s14:2_6.png }}+  ​-Open the project.
-Generally, with stock assets and view controllers,​ we set the titles of controllers to expose which part of the app the user is onThough not strictly necessary, they will make the structure of the app more clear in the upcoming steps+{{ ios-labs-s14:​2_34.png }} 
 +{{ ios-labs-s14:​2_32.png }} 
 +{{ ios-labs-s14:​2_33.png }}
-Repeat the instructions ​above for the other view controllers so they match the second screenshot.+===== Miscellaneous ===== 
 +The following ​instructions ​address a few lapses from the first lecture. All of these steps are optional
 +You never learned how to use the debugger or how to diagnose crashes, so a quick overview of a crash is shown. ​
 +Finally, you may have noticed some clipping between your storyboard setup and the simulator. Storyboard shows 4 inch view controllers (iPhone 5 and later), but the standard simulator is the 3.5 inch version (pre iPhone 5). Storyboard is absolutely deterministic;​ if you'd like to fix the clipping you'll have to switch the simulator.
 +=== Debugging ====
 +  -Active Threads
 +  -The second button from the right toggles the bottom debugging pane
 +  -The Console. Upon crashing, the device will print the reason for the crash as well as a stack dump. Scroll up until you see "​Terminating app due to uncaught exception...."​ This is the reason your app crashed.
 +  -A visual object inspector, allowing you to look through all variables in memory
 +  -Hit the folder button to get back to the project navigator
 +{{ios-labs-s14:​2_16.png }}
 +===Changing Simulator Size===
 +  -To the right of the Play button in the top left corner is the name of your application. To the right of that is a blue icon with the name of the active simulator.
 +  -Click this, select "​iPhone Retina (4-inch)"​
 +{{ ios-labs-s14:​2_0.png }}
 +===Dealing with an Unresponsive InterfaceBuilder===
 +Have you tried dragging a view onto a controller only to have it snap back to the menu? InterfaceBuilder will only allow you to drag views onto controllers that it thinks are "in focus."​ If you can't drag a view in, double click on the controller to zoom in, or use the zoom buttons on the bottom right of the storyboard.
 ---- ----
-====== ​Subclassing ViewControllers ​====== +====== ​Tutorial - A Primer on Segues  ​====== 
-There'​s one big problem ​with the app as designed ​so farIf you've been paying attention, you may have anticipated it by now+I have observed a lot of students still struggling ​with Segues in the labs, so here is a much more detailed explanation on Segues and how to use themhave also added some links to relevant resources in the end
-Think back to the last lecturewhen you connected the "​Greeting"​ button and label on the original view controllerAfter making an IBOutlet ​and IBAction in the //​ViewController.h// filewe added code in //​ViewController.m//​ to respond to the button press.+Typically, you need just one storyboard per appThis storyboard comprises of two important ideas, scenes ​and seguesWith a single view appyou begin with just one scene and viewcontroller and then create a new scene for each screen ​in your app.
-Now there are 4 view controllers on the screenIn the project navigator, you can see there is only one //​ViewController//​ class. How do we connect IBConnections ​from each individual view controller to code? Do they all go to the same source code files? How can we tell which view controller is active?+Now, we need a way to transition between two scenes, how do we do that? That is where segues come into picture. You describe segues between ​the relevant scenesSegues define nothing but how the visual transitions would look like on switching view controllerslike do you want them to move in from the right, ​do a flip, fly from the left etc.
-The answers are: can'tno, **subclassing.** In Java (or any object-oriented language) you rarely code inside of stock objects: you don't start editing Java String class when you need to change its behavior, you subclass it. In iOS, every controller is subclass of UIViewController. The object we coded in last time is an auto-generated subclass called ViewControllerWhen controller appears on the screenthe source code associated with it is instantiated and brought into memory. Although the source code files on the left seem separate from the view controllers ​in InterfaceBuilder,​ **they are one and the same.**+Segues as what you have seen till nowlike when you were developing the mighty Quiz app only works if user interacts with the screen ​in some wayOne can also trigger ​segue programmaticallysay in response to a gesture or a change in accelerometer
-In order to connect all the views we added in the last lecture ​to code, we have to create new UIViewController subclasses for each controller shown in InterfaceBuilder and then inform InterfaceBuilder which source code it should associate with controllers.+Let's directly get into action. I am going to make a 3 scene app and use segues ​to show transition between them.
 +Initially in the story board, we will begin with one scene. This scene loads when the application begins. You add new scenes by finding the view controllers in your object library and dragging one onto the canvas. Zoom out, so that you can see the entire storyboard. Select a view controller in the object library and then drag it inside the storyboard, doesn'​t matter where you position these. I have positioned the three VC side by side.
-Remember, the app will have 4 ViewControllers:​+When the transition happens I want to be able to see the difference between these 3 VCso I am going to change the background color for two of them. To do that Zoom Back in and go to the attributes inspector tab. It looks like a tuxedo on the top right. Change ​the background to whatever you want.
-  *Home- this is the controller you already have on the screenUsers will use this as springboard ​to access ​the rest of the appThis will be the first controller ​to appear. Contains two buttons ​that transition ​to Settins and PostsSince this has already been implemented,​ we will not add it again and leave the name as **ViewController.** (Note: this is bad style) +Next, let's add segueing between themThe segue needs to be triggered using something, let'​s ​use a button ​to do that. Find the button in the object library, drag that into the first and second VCChange ​the text to Next VC coz that's exactly what we intend ​to doI haven'​t put any button on the third screenI just want the transition from the first VC to the second on button click and then go from the second ​to the third
-  *Settings- users can set the number of posts to display in the Posts controller here. It will be called **SettingsViewController.** +
-  *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. Name: **PostsViewController** +
-  *Images- display the Instagram image and the comment below it. **ImagesViewController.**+
-Note how annoyingly verbose the above names areIt may be revolting at first, ​but just drink the Kool-Aidyou get used to it+How do we do this, to make segues we don't need to worry about IB action or anything like thatI simply take the first view controllerclick on the buttonpress the control key and drag to the second view controller while holding the key down. Let go! You would see a pop up come up. With iOS 8, segues have become adaptive which means iOS is going to be intelligent in detecting device and screen size. Let's stick to the show segue for the time being. You would observer a little arrow show up in between the two VC. Do exactly the same for the 2nd and 3rd view controller.
 +Ok, now do Command R. Let's just run this. Click on the button, you would see them move. Voila! This is how segues work.
-===Creating ​the SettingsViewController subclass of UIViewController=== +Here are the screenshots 
-  -Go to File > New > File +{{ :ios-labs-f15:​screen_shot_2015-10-12_at_4.02.57_pm.png }} 
-  -Ensure the category is "Cocoa Touch" and the template is "​Objective-C class." Click "​Next"​ +{{ :ios-labs-f15:​screen_shot_2015-10-12_at_4.06.53_pm.png }} 
-  -Enter "​SettingsViewController"​ in the class field and ensure that "​subclass of" is UIViewControllerClick next and then create.+{{ :ios-labs-f15:​screen_shot_2015-10-12_at_4.11.05_pm.png }} 
 +{{ :​ios-labs-f15:​screen_shot_2015-10-12_at_4.19.46_pm.png }} 
 +{{ :​ios-labs-f15:​screen_shot_2015-10-12_at_4.20.21_pm.png }}
-{{ ios-labs-s14:​2_7.png }} +====== Tutorial ​UITableViewController ​ ======
-{{ ios-labs-s14:​2_8.png }} +
-{{ ios-labs-s14:​2_9.png }}+
-This example demonstrates how to subclass ​UIViewController specifically ​for SettingsViewController;​ change the name and repeat the process for the other view controllers with the names listed above+This will be simple tutorial ​for UITableViewController ​and UITableViewCell
-{{ ios-labs-s14:​2_12.png }}+1.first drag one UITableViewController on to the storyboard, set it as initial view controller if u start with a template and don't what to do segue
-Note the new source code files visible in the project navigator. Each time you create a view controller the source code files are added to the existing project. One  step separates us from actually using the view controllers,​ however. We must let InterfaceBuilder know that the view controllers placed in the storyboard are the subclasses we just created. Without an explicit assignment InterfaceBuilder cannot tell which new class should be associated with which view controller.+{{:​ios-labs-f15:​x1.png|}}
-Note: when clicking on the body of a ViewControllerXcode thinks you want to click on the ViewController'​s views; notice that whatever is highlighted blue is what is currently selected. To select an entire ​controller, click right at the very top of the rectangle in your storyboard: this is the status barand always refers ​to the controller below it. If you have the //Identity Inspector// tab open in the right pane and you're working ​with a stock controller, ​the "​Class"​ field should read "UIViewController" when you have selected the right thing. If it says "​UIView"​ or anything else, try again.+2.  Now lets understand what we have hereso the controller ​you have here is a UITableViewControllerits similar ​to UIViewController ​you have been using before, but only with a pre connected UITableView which will fill the entire ​UIViewController. ​
-===Change View Controller Classes=== +You can defiantly achieve ​the same thing with UIViewController+ UITableView, ​the difference is:
-  -Select ​the storyboard file to bring up InterfaceBuilder +
-  -Click on the settings view controller. Select the identity inspector in the right-hand pane +
-  -Enter the name of the subclass as pictured.+
-{{ ios-labs-s14:2_11.png }}+**UITableViewController** ​table will be full screen, but delegate are pre linked.
-Repeat these steps for each controller on the storyboard.+**UIViewController+ UITableView** : table can resize, has to manually link delegate and add delegate code
-===== Connecting new IBOutlets ===== +but remember they are different ​controllers ​so make sure when u create your swift choose ​the right one
-Even though the views are present in the view controller'​s views, the controllers' code still don't have access to the views. These instructions will not be as explicit as last lecture. If you can't remember how to connect IBOutlets, please check the previous lecture. ​+
-===Connect SettingsViewController Outlets=== +3. When you double click the white area of the prototype cellsit will do the followingthis is called a UITableViewCell, ​and it serves ​as template and can be reused
-  -Select ​the SettingsViewController in storyboardopen the Assistant Editorand insure the header file is selected (*.h) +
-  -Enter the curly braces ​and right-click drag from the text field to within the braces. Enter //​textfieldNumberOfImages// ​as the name +
-{{ ios-labs-s14:​2_13.png }}+
-Repeat these steps for Images and Posts view controllers. ImagesViewController is shown below.  +{{:ios-labs-f15:x2.png|}}
-{{ ios-labs-s14:2_14.png }} +
-====== Tables ====== +Lets drag a label in hereremember **you also have to do auto layout inside ​the cell**
-You can't go too far in an iOS project without stumbling over a few tables. They are too useful to ignoreand too complex ​to replace yourself. Although a table is not the most useful view for this project, it is more simple than the alternative and far more common (the alternative is a UICollectionView.)+
-===== Delegation ===== +{{:ios-labs-f15:x3.png|}}
-Delegation is the process of assigning another object to handle the administrative tasks of a given object. Some objects in Objective-C will crash your app if their delegate has not been assigned, tables are one of these. At its most basic, delegation protects MVC and makes your life as a developer much easier. I'll go ahead and spoil something for youyou do not want to mess with UITableView source code+
-Instead, we rely on stock UITableViews and customize their behavior by assigning //​delegate//​ and //data source.// By doing this, the table will call a known set of methods ​on the delegate ​when it has questions about how it should behave. In order to complete the connection, we must implement those methods in the delegate.+now lets check on the delegate, ​because ​we are using **UITableViewController** they are pre linked
-===Setting a Table Delegate=== +{{:ios-labs-f15:x4.png|}}
-  -Select the ImagesViewController in Storyboard. Expose the view controller'​s heirarchy by clicking the //Document Outline// button (circled below.) This exposes the explicit heirarchy of views for this controller.  +
-  -Select the table and right click +
-  -Drag from the //​delegate//​ circle to the yellow //​ImagesViewController//​ entry in the outline opened on the left. See screenshot.  +
-  -Repeat last two instructions,​ but dragging from //​dataSource//​ instead. +
-{{ ios-labs-s14:2_15.png }}+
-Seem cumbersome? Maybe, but just like last time you've performed all of the steps needed to create tables. Without informing the table what its delegate ​and dataSource should be, it has no idea where to look for its internal data. Now, the ImagesViewController has to implement the delegate methods so it can appropriately serve that data. +There are two delegate ​u need to link if you are doing UIViewController+ UITableView
-===Implementing Table Delegate and Data Source Methods=== +**UITableViewDelegate 
-  -Open //​ImagesViewController.m//​ +UITableViewDataSource**
-  -Copy the code below before the //@end// in the file. See screenshot. +
-<​code>​ +
-#pragma mark Table Delegate +
-- (NSInteger)numberOfSectionsInTableView:​(UITableView ​*)tableView +
-    return 1; +
-- (NSInteger)tableView:​(UITableView *)tableView numberOfRowsInSection:​(NSInteger)section +4. create the swift files we need, make sure to choose the right subclass
-    return 10; +
-- (UITableViewCell ​*)tableView:​(UITableView ​*)tableView cellForRowAtIndexPath:​(NSIndexPath ​*)indexPath +**UITableViewController**
-    UITableViewCell ​*cell = [tableView dequeueReusableCellWithIdentifier:​@"​cell"​];​ +
-     +
-    if (cell == nil) { +
-        cell = [[UITableViewCell alloc] initWithStyle:​UITableViewCellStyleSubtitle reuseIdentifier:​@"​cell"​];​ +
-    } +
-     +
-    return cell; +
-#pragma mark Tableview Data Source +{{:ios-labs-f15:x6.png|}}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:​(NSIndexPath *)indexPath +
-    [tableView deselectRowAtIndexPath:​indexPath animated:​YES];​ +
-} +
-{{ ios-labs-s14:​2_17.png }}+**UITableViewCell**
-There'​s one more (rather unfortunate) step left in assigning the table cells to the table. In order for the table to save memory, it doesn'​t delete cells that no longer appear on the screen, it simply reuses them again. In order to reuse the right cell, a reuse identifier must be set.+{{:​ios-labs-f15:​x7.png|}}
-===Setting a Reuse Identifier=== +Link **UITableViewController**
-  -Open storyboard. Go to the Attributes Inspector. +
-  -Select the static table cell +
-  -In the //​Identifier//​ field, enter "​cell"​ +
-{{ ios-labs-s14:​2_18.png }}+
-Now we're ready to test the table! If you run it now, you should see nothing, just 10 blank cells. To test, we're going to set the fields of the cell with some obvious dummy data. Here you're going to have to do a spot of coding yourself. There are two lines you must add, one to set the text of the main label and one to set the text of the sublabel (both are subviews of the table cell.) I won't write it out for you, but I'll give you a few hints. These lines should be put right before //return cell// in the //​cellForRowAtIndexPath//​ method. See screenshot below for result.+{{:​ios-labs-f15:​x8.png|}}
-  -The two labels you must access are called //​textLabel//​ and //​detailTextLabel//​ +Link **UITableViewCell**
-  -You can access each using the dot operator on the //cell// object +
-  -You used the method needed to change the text of a label in the previous lecture. The code is in ViewController.m or on the previous tutorial page +
-  -The method above takes an NSString as an argument. You create string literals using //​@"​texthere"//​+
-Make each row of the table display some data you set using the above lines to prove everything works. For extra credit: +{{:ios-labs-f15:x9.png|}}
-  ​-Set each row's label'​s dynamically. //​indexPath//​ shows the current index and column, //​indexPath.row//​ shows the current index as an integer +
-  ​-Remember, you'll have to pass a string to the label'​s text changing methodTo include a number within the string, you'll have to create another string using //​NSString//'​s class method called //​stringWithFormat://​+
-===== Testing the Table ===== +One More Thing!!! **Make sure to set a identifier for your UITableViewCell** 
-   ​-Enter the lines of code above and run the app. It should like like the screenshot (noteextra credit shown.) + 
-{{ ios-labs-s14:2_19.png }} +{{:ios-labs-f15:​x10.png|}} 
 +5.  Swift code for UITableViewCell 
 +Create ​and IBOutlet for the label that we created, so that we can change it in the UITableViewController 
 +6. Swift code for UITableViewController 
 +**numberOfSectionsInTableView**:​ how many section you want in your tableview (Need at least 1) 
 +**numberOfRowsInSection**:​ how many rows we want (be sure to be correspond to ur data) 
 +I created a **var items = ["text 1","​text 2","​text 3","​text 4","​text 5"]** so that I have some fake data 
 +now uncomment the next function, and do this 
 +make sure the identifier is what you have setup earlier. 
 +7. Run it and... 
-====== Conclusion ====== +DONE!!
-That's all for part twoYou should have learned just a bit of Objective-C,​ but more importantly grown a little more comfortable with it. In the next lecture we will connect to the Instagram Server, parse the response, and load the data into the app. +
android-labs-s16/ios_tutorial_2.1453774515.txt.gz · Last modified: 2016/01/25 20:15 by mbarboi