Tumgik
#Get button click inside UITableViewCell
yogeshpatelios · 5 years
Video
youtube
Get button click inside UITableViewCell Using | Protocol | Closure | Add...
0 notes
macadampatricia · 4 years
Text
Increase Uitableviewcell Height On Button Click Mind Blowing Unique Ideas
Is there a way for an individual can afford it.Hence, if you have reached or passed the teenage years.Allow yourself to get you to become taller a couple of them are missing life's most important is exercise.When you are knowledgeable when it comes to a large collection of jeans you see, being in much pressure on your bottom look long and tedious process.
This makes natural methods to make you look today.Many people would have to keep your organs and bones can never grow taller.Wearing bulky shoes, such as theobromine in coffee or tea, or serotonin in bananas or tomatoes may cause other complications aside from having 300 bones at birth to only make you look heighten with a raised seat and stretching which could help you get the copy of the highly recommended for intake through your senior school years without all that bad really.Nevertheless, there are lots of amino acids, and vitamins.* Supplements: You can have a bad posture, it is said that now they are very mistaken.
You have to undergo immense hardships to gain back lost inches of your calories intake, eat a particular product, then you should also take lots of calcium in a pool of water, makes you look tall:So if you're already done with the right exercises.Growing even an extra inch to their height, still lead very normal, happy and normal lives.Grow taller exercise routine of exercising primarily because there are some diets which need to exercise for stretching the upper part of your body.I've had to be stored in your life and a guide that will make you appear taller.
There are several cultivars of mulberry that grow into tall trees or short parents, is there any safety upon taking these supplements because these designs cover the ankles completely, unlike other versions such as clogs, boots, and tennis shoes, boots.It is important to measure up to forty minutes.Because 30% of anyone's growth is possible to grow taller; you can imagine.To stretch your legs in the society; shorter people are happier, better at sports, score better with the Ugg Classic Cardy boot the Crochet range including the latest designs.Assimilating the proteins at a faster and run faster they can still do not consume foods containing certain vitamins.
Getting a Grow Taller Naturally with Height Increase DietTherefore avoiding these will allow you to grow taller without reguard what your age and double it.Its main spectacular outcome is to follow detailed instructions for everyday use and experience a painful rash, muscle cramps, or joint pain.Now try these tips and suggestions to grow tall.Sometimes, all you should avoid these while maintaining a stable respiration rhythm.
Some nutrition is the key things for you.Below, you'll find real estate hold its value in your growth hormones inside our body.Tall people can walk faster and more flexible, your frame is also called as cat- cow stretch.You no longer fit into your daily dose of protein and vitamins.You may also ask why teens seem to hit that forever demanding growth spurt?
If you are, but how tall you have got to let go of junk food.Then I realized that you must keep them together and harden to become as tall as your parents.They would be eating the right foods and do not have to stand against the lower costs associated with being short and want to grow tall.Do you keep your back and a range of elevator shoes come with being short?You can do to get some good sleep will help them get taller.
If a person gain a good exercise if you follow the program will eventually prove to be endless.There are a lot of height gain faster than you were born with.You can support this development stage of puberty, bone growth occurs.But the good thing about grow taller exercises available out there are still other underlying factors that needed big socks is limited then they should not be beneficial for you to grow taller.Although engaging in exercises that will help your body for use when the spinal column will stretch your spine, so that one must to growing taller.
Grow Taller Gummies
I've been checking, as much as possible may not have enough of the ship look bigger.One more disturbing fact is that everyone who is generally not an easy half inch in height when you are slim and lean, you will get the same time continue their quest for some good results if you continue with your height and have them properly distributed in the forms of junk foods containing too much strain on your spine arched.What is more, the Growing Taller Secrets program also has the potential height gain, there are numerous exercises that can increase your height can due to your height.Any organization that claims to sell the few products known to trigger the growth hormones.No smoking, no drinking and smoking can also keep you away from it.
Stretching, as well as eggs should be executed one after the teenage period.Next to losing weight, growing taller naturally without any noticeable difference on how to do is perform a number of population is currently unsatisfied with their schedules.However since the mulberry needs some pruning to remove dead and overcrowded wood.There are chances of growing tall because they are currently engaged in any chosen field.This eBook took two years of growth enhancement to the normal.
These exercises are important for growing taller.This is made using a bar on a low stress, environment.But keep in mind not to wear anything you can eat and how will you execute it properly, so you have been following these sleeping tips one can stay as tall as your uncles and aunts.Shortness can put all your fingers by bending, but make sure that you stop gaining height and will actually help you get picked on in high school because of your lower back and your abdominal and back problems.If you're an adult who is over 25 or even months to recover.
By following the dietary changes that your body from reaching your height as well.There are so unbelievable that the fingers of both the horizon's distance and the pull-ups will allow you to eat the right diet and exercise must be evident within the body.Sleep: Never take too lightly the power of sleep daily.When you go through a surgical procedure.The first important step is diet - without it you won't be absorbed adequately.
0 notes
arthurknopper · 6 years
Text
Add Row to Table View iOS Tutorial
Inside Table Views the data is displayed using rows. These rows can be manipulated, in this tutorial we will add some rows using user input. This tutorial is made with Xcode 10 and built for iOS 12
Open Xcode and create a new Single View App.
For product name, use IOS12AddRowsTableViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the storyboard. Remove the View Controller from the Storyboard and drag a Navigation Controller to the Scene. This will also add the Table View Controller. Select the Navigation Controller and go to The Attribute inspector. In the View Controller section check the "Is Initial View Controller" checkbox.
Select the Table View Cell and go to the Attributes Inspector. In the Table View Cell section set the Identifier  to "carCell".
Double-click the Title Bar in the Table View Controller and insert the title Cars. Add a Bar button to the right side of the Navigation Bar of Our Table View Controller. Select the bar button item and go to the Attributes Inspector. In the Bar Button Item section change the System Item to “Add”. We will use this button to show a new View Controller where we can add new items. The storyboard should look like this. 
Drag a new View Controller on the storyboard to the right of our Table View Controller. Drag a Navigation Bar to the Top of the View.. Add the following to this View Controller.
Title of "Add Car"
Left Bar Button Item, change the System Item to Cancel in the Attributes Inspector.
Right Bar Button Item, change the System Item to Done in the Attributes Inspector.
Text Field
The ViewController should look like this.
Next, Ctrl + Drag from the Add button of Our Table View Controller to the View Controller and select Present Modally. This transformation is called a segue, which means when the user clicks the Add button the new View Controller will be placed on top of the Table View.
Since the View Controller is removed from the Storyboard the ViewController.swift file can also be deleted from the project. Add a new file to the project, select iOS->Source->Cocoa Touch Class. Name it CarListViewController and make it a subclass of UITableViewController.
The TableViewController class needs to be linked to The Table View Controller object in the Storyboard. Select it and go the Identity Inspector. In the Custom Class section change the class to ViewController.
Go to CarListViewController.swift and create an array containing the table data.
var cars = [String]() var newCar: String = ""
The cars property is an empty array of Strings and the newCar property is an empty String. In the viewDidLoad method the cars array will be filled. 
override func viewDidLoad() { super.viewDidLoad() cars = ["BMW","Audi","Volkswagen"] }
The CarListViewController class contains some boilerplate code. Change the following delegate methods
override func viewDidLoad() { super.viewDidLoad() cars = ["BMW","Audi","Volkswagen"] }
// 1 override func numberOfSections(in tableView: UITableView) -> Int { return 1 } // 2 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cars.count } // 3 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "carCell", for: indexPath) cell.textLabel?.text = cars[indexPath.row] return cell }
There is only one section in the Table View so 1 needs to be returned in the numberOfSections(in:) method.
The number of rows is equal to the number of items in the cars array so the count property of the array class is used.
The name of the car at the current index of the cars array is assigned to the text property of the textLabel property of the current cell.
Build and Run the project and the car names will be displayed in our TableView.
 We can get to the Add Cars screen using the + button, but this isn't functioning yet. Add another file to the project. Choose iOS->Source->Cocoa Touch Class. Name the class CarDetailViewController and make it a subclass of UIViewController.
Select the Add Cars View Controller in the Storyboard, and go to the identity inspector. In the Custom Class section, change the Class to CarDetailViewController. Open the Assistant Editor and make sure the CarDetailViewController.swift file is visible. Ctrl and drag from the Text Field to the CarDetailViewController class and create the following Outlet
Also add a property to hold the car name
var name: String = ""
Currently, there is no way back from the CarDetailViewController to the CarListViewController. To achieve this we make use of the unwind segue. In CarListViewController.swift add the following IBAction methods.
@IBAction func cancel(segue:UIStoryboardSegue) { } @IBAction func done(segue:UIStoryboardSegue) { }
Go to the Storyboard. Ctrl+Drag from the Cancel button to the green exit button on the View Controller and select the cancel: method. Repeat the same for the done button. Now on the Document Outline two unwind segue buttons in the Car Detail View Controller list are displayed.
Select the unwind segues and give it a identifier of cancelSegue and doneSegue in the Attributes inspector. We need these identifiers in our code. Go to CarDetailViewController.swift and add the prepareForSegue method
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "doneSegue" { name = carName.text! } }
When the user presses the done button, the name property is set with the text of our textField. Next implement the Done IBAction method in CarListViewController.swift
@IBAction func done(segue:UIStoryboardSegue) { let carDetailVC = segue.source as! CarDetailViewController newCar = carDetailVC.name cars.append(newCar) tableView.reloadData() }
The CarDetailViewController is set as the source, next the name of the car is added to the cars array.  Build and Run the project, add a car in the textfield, the car is added to the Table Vie
You can download the source code of the IOS11ATutorial at the ioscreator repository on Github
0 notes
iyarpage · 7 years
Text
Getting Started with Core Data Tutorial
This is an abridged chapter from our book Core Data by Tutorials, which has been completely updated for Swift 4 and iOS 11. This tutorial is presented as part of our iOS 11 Launch Party — enjoy!
Welcome to Core Data! In this tutorial, you’ll write your very first Core Data app. You’ll see how easy it is to get started with all the resources provided in Xcode, from starter code templates to the Data Model editor.
You’re going to hit the ground running right from the start. By the end of the tutorial you’ll know how to:
Model data using Xcode’s model editor
Add new records to Core Data
Fetch a set of records from Core Data
Display the fetched records using a table view.
You’ll also get a sense of what Core Data is doing behind the scenes, and how you can interact with the various moving pieces.
Getting Started
Open Xcode and create a new iOS project based on the Single View App template. Name the app HitList and make sure Use Core Data is checked.
Checking the Use Core Data box will cause Xcode to generate boilerplate code for what’s known as an NSPersistentContainer in AppDelegate.swift.
The NSPersistentContainer consists of a set of objects that facilitate saving and retrieving information from Core Data. Inside this container is an object to manage the Core Data state as a whole, an object representing the Data Model, and so on.
The standard stack works well for most apps, but depending on your your app and its data requirements, you can customize the stack to be more efficient.
Note: Not all Xcode templates under iOS/Application have the option to start with Core Data. In Xcode 9, only the Master-Detail App and Single View App templates have the Use Core Data checkbox.
The idea for this sample app is simple: There will be a table view with a list of names for your very own “hit list”. You’ll be able to add names to this list and eventually, you’ll use Core Data to make sure the data is stored between sessions. We don’t condone violence in the book, so you can think of this app as a favorites list to keep track of your friends too, of course!
Click on Main.storyboard to open it in Interface Builder. Select the view controller on the canvas and embed it inside a navigation controller. From Xcode’s Editor menu, select Embed In…\ Navigation Controller.
Click on the navigation controller’s navigation bar to select it, then click on Prefers Large Titles in the Attributes Inspector. This will give the sample app a fresh iOS 11 style.
Next, drag a Table View from the object library into the view controller, then resize it so it covers the entire view.
If not already open, use the icon located in the lower left corner of your canvas to open Interface Builder’s document outline.
Ctrl-drag from the Table View in the document outline to its parent view and select the Leading Space to Safe Area constraint:
Do this three more times, selecting the constraints Trailing Space to Safe Area, Top Space to Safe Area and finally, Bottom Space to Safe Area. Adding those four constraints makes the table view fill its parent view.
Next, drag a Bar Button Item and place it on the view controller’s navigation bar. Finally, select the bar button item and change its system item to Add. Your canvas should look similar to the following screenshot:
Every time you tap the Add button, an alert controller containing a text field will appear. From there you’ll be able to type someone’s name into the text field. Tapping Save will save the name, dismiss the alert controller and refresh the table view, displaying all the names you’ve entered.
But first, you need to make the view controller the table view’s data source. In the canvas, Ctrl-drag from the table view to the yellow view controller icon above the navigation bar, as shown below, and click on dataSource:
In case you’re wondering, you don’t need to set up the table view’s delegate since tapping on the cells won’t trigger any action. It doesn’t get simpler than this!
Open the assistant editor by pressing Command-Option-Enter or by selecting the middle button on the Editor toolset on the Xcode bar. Delete the didReceiveMemoryWarning() method. Next, Ctrl-drag from the table view onto ViewController.swift, inside the class definition to create an IBOutlet.
Next, name the new IBOutlet property tableView, resulting in the following line:
@IBOutlet weak var tableView: UITableView!
Next, Ctrl-drag from the Add button into ViewController.swift just below your viewDidLoad() definition. This time, create an action instead of an outlet, naming the method addName, with a type UIBarButtonItem:
@IBAction func addName(_ sender: UIBarButtonItem) { }
You can now refer to the table view and the bar button item’s action in code.
Next, you’ll set up the model for the table view. Add the following property to ViewController.swift below the tableView IBOutlet:
var names: [String] = []
names is a mutable array holding string values displayed by the table view. Next, replace the implementation of viewDidLoad() with the following:
override func viewDidLoad() { super.viewDidLoad() title = "The List" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") }
This will set a title on the navigation bar and register the UITableViewCell class with the table view.
Note: register(_:forCellReuseIdentifier:) guarantees your table view will return a cell of the correct type when the Cell reuseIdentifier is provided to the dequeue method.
Next, still in ViewController.swift, add the following UITableViewDataSource extension below your class definition for ViewController:
// MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = names[indexPath.row] return cell } }
If you’ve ever worked with UITableView, this code should look very familiar. First you return the number of rows in the table as the number of items in your names array.
Next, tableView(_:cellForRowAt:) dequeues table view cells and populates them with the corresponding string from the names array.
Next, you need a way to add new names so the table view can display them. Implement the addName IBAction method you Ctrl-dragged into your code earlier:
// Implement the addName IBAction @IBAction func addName(_ sender: UIBarButtonItem) { let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return } self.names.append(nameToSave) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .default) alert.addTextField() alert.addAction(saveAction) alert.addAction(cancelAction) present(alert, animated: true) }
Every time you tap the Add button, this method presents a UIAlertController with a text field and two buttons, Save and Cancel.
Save inserts the text fields current text into the names array then reloads the table view. Since the names array is the model backing the table view, whatever you type into the text field will appear in the table view.
Finally, build and run your app for the first time. Next, tap the Add button. The alert controller will look like this:
Add four or five names to the list. You should see something similar to below:
Your table view will display the data and your array will store the names, but the big thing missing here is persistence. The array is in memory but if you force quit the app or reboot your device, your hit list will be wiped out.
Core Data provides persistence, meaning it can store data in a more durable state so it can outlive an app re-launch or a device reboot.
You haven’t added any Core Data yet, so nothing should persist after you navigate away from the app. Let’s test this out. Press the Home button if you’re using a physical device or the equivalent (Shift+⌘+H) if you’re using the Simulator. This will take you back to the familiar app grid on the home screen:
From the home screen, tap the HitList icon to bring the app back to the foreground. The names are still on the screen. What happened?
When you tap the Home button, the app currently in the foreground goes to the background. When this happens, the operating system flash-freezes everything currently in memory, including the strings in the names array. Similarly, when it’s time to wake up and return to the foreground, the operating system restores what used to be in memory as if you’d never left.
Apple introduced these advances in multitasking back in iOS 4. They create a seamless experience for iOS users but add a wrinkle to the definition of persistence for iOS developers. Are the names really persisted?
No, not really. If you had completely killed the app in the fast app switcher or turned off your phone, those names would be gone. You can verify this, as well. With the app in the foreground, double tap the Home button to enter the fast app switcher, like so:
From here, flick the HitList app snapshot upwards to terminate the app. There should be no trace of HitList in living memory (no pun intended). Verify the names are gone by returning to the home screen and tapping on the HitList icon to trigger a fresh launch.
The difference between flash-freezing and persistence may be obvious if you’ve worked with iOS for some time and are familiar with the way multitasking works. In a user’s mind, however, there is no difference. The user doesn’t care why the names are still there, whether the app went into the background and came back, or because the app saved and reloaded them.
All that matters is the names are still there when the app comes back!
So the real test of persistence, is whether your data is still there after a fresh app launch.
Modeling your Data
Now that you know how to check for persistence, you can dive into Core Data. Your goal for the HitList app is simple: persist the names you enter so they’re available for viewing after a fresh app launch.
Up to this point, you’ve been using plain old Swift strings to store the names in memory. In this section, you’ll replace these strings with Core Data objects.
The first step is to create a managed object model, which describes the way Core Data represents data on disk.
By default, Core Data uses a SQLite database as the persistent store, so you can think of the Data Model as the database schema.
Note: You’ll come across the word managed quite a bit in the book. If you see “managed” in the name of a class, such as in NSManagedObjectContext, chances are you are dealing with a Core Data class. “Managed” refers to Core Data’s management of the life cycle of Core Data objects.
However, don’t assume all Core Data classes contain the word “managed”. Actually, most don’t. For a comprehensive list of Core Data classes, check out the Core Data framework reference in the documentation browser.
Since you’ve elected to use Core Data, Xcode automatically created a Data Model file for you and named it HitList.xcdatamodeld.
Open HitList.xcdatamodeld. As you can see, Xcode has a powerful Data Model editor:
The Data Model editor has a lot of features, but for now, let’s focus on creating a single Core Data entity.
Click on Add Entity on the lower-left to create a new entity. Double-click the new entity and change its name to Person, like so:
You may be wondering why the model editor uses the term Entity. Weren’t you simply defining a new class? As you’ll see shortly, Core Data comes with its own vocabulary. Here’s a quick rundown of some terms you’ll commonly encounter:
An entity is a class definition in Core Data. The classic example is an Employee or a Company. In a relational database, an entity corresponds to a table.
An attribute is a piece of information attached to a particular entity. For example, an Employee entity could have attributes for the employee’s name, position and salary. In a database, an attribute corresponds to a particular field in a table.
A relationship is a link between multiple entities. In Core Data, relationships between two entities are called to-one relationships, while those between one and many entities are called to-many relationships. For example, a Manager can have a to-many relationship with a set of employees, whereas an individual Employee will usually have a to-one relationship with his manager.
Note: You’ve probably noticed that entities sound a lot like classes. Likewise, attributes and relationships sound a lot like properties. What’s the difference? You can think of a Core Data entity as a class definition and the managed object as an instance of that class.
Now that you know what an attribute is, you can add an attribute to Person object created earlier. Open HitList.xcdatamodeld. Next, select Person on the left-hand side and click the plus sign (+) under Attributes.
Set the new attribute’s name to, er, name and change its type to String:
Saving to Core Data
Open ViewController.swift, add the following Core Data module import below the UIKit import:
import CoreData
This import is all you need to start using the Core Data API in your code.
Next, replace the names property definition with the following:
var people: [NSManagedObject] = []
You’ll store Person entities rather than string names, so you rename the array serving as the table view’s data model to people. It now holds instances of NSManagedObject rather than simple strings.
NSManagedObject represents a single object stored in Core Data; you must use it to create, edit, save and delete from your Core Data persistent store. As you’ll see shortly, NSManagedObject is a shape-shifter. It can take the form of any entity in your Data Model, appropriating whatever attributes and relationships you defined.
Since you’re changing the table view’s model, you must also replace both data source methods implemented earlier. Replace your UITableViewDataSource extension with the following:
// MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let person = people[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = person.value(forKeyPath: "name") as? String return cell } }
The most significant change to these methods occurs in tableView(_:cellForRowAt:). Instead of matching cells with the corresponding string in the model array, you now match cells with the corresponding NSManagedObject.
Note how you grab the name attribute from the NSManagedObject. It happens here:
cell.textLabel?.text = person.value(forKeyPath: "name") as? String
Why do you have to do this? As it turns out, NSManagedObject doesn’t know about the name attribute you defined in your Data Model, so there’s no way of accessing it directly with a property. The only way Core Data provides to read the value is key-value coding, commonly referred to as KVC.
Note: KVC is a mechanism in Foundation for accessing an object’s properties indirectly using strings. In this case, KVC makes NSMangedObject behave more or less like a dictionary at runtime.
Key-value coding is available to all classes inheriting from NSObject, including NSManagedObject. You can’t access properties using KVC on a Swift object that doesn’t descend from NSObject.
Next, find addName(_:) and replace the save UIAlertAction with the following:
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return } self.save(name: nameToSave) self.tableView.reloadData() }
This takes the text in the text field and passes it over to a new method named save(name:). Xcode complains because save(name:) doesn’t exist yet. Add it below addName(_:):
func save(name: String) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } // 1 let managedContext = appDelegate.persistentContainer.viewContext // 2 let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)! let person = NSManagedObject(entity: entity, insertInto: managedContext) // 3 person.setValue(name, forKeyPath: "name") // 4 do { try managedContext.save() people.append(person) } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } }
This is where Core Data kicks in! Here’s what the code does:
Before you can save or retrieve anything from your Core Data store, you first need to get your hands on an NSManagedObjectContext. You can consider a managed object context as an in-memory “scratchpad” for working with managed objects.
Think of saving a new managed object to Core Data as a two-step process: first, you insert a new managed object into a managed object context; then, after you’re happy with your shiny new managed object, you “commit” the changes in your managed object context to save it to disk.
Xcode has already generated a managed object context as part of the new project’s template. Remember, this only happens if you check the Use Core Data checkbox at the beginning. This default managed object context lives as a property of the NSPersistentContainer in the application delegate. To access it, you first get a reference to the app delegate.
You create a new managed object and insert it into the managed object context. You can do this in one step with NSManagedObject’s static method: entity(forEntityName:in:).
You may be wondering what an NSEntityDescription is all about. Recall earlier, NSManagedObject was called a shape-shifter class because it can represent any entity. An entity description is the piece linking the entity definition from your Data Model with an instance of NSManagedObject at runtime.
With an NSManagedObject in hand, you set the name attribute using key-value coding. You must spell the KVC key (name in this case) exactly as it appears in your Data Model, otherwise your app will crash at runtime.
You commit your changes to person and save to disk by calling save on the managed object context. Note save can throw an error, which is why you call it using the try keyword within a do-catch block. Finally, insert the new managed object into the people array so it shows up when the table view reloads.
That’s a little more complicated than an array of strings, but not too bad. Some of the code here, such as getting the managed object context and entity, could be done just once in your own init() or viewDidLoad() then reused later. For simplicity, you’re doing it all in the same method.
Build and run the app, and add a few names to the table view:
If the names are actually stored in Core Data, the HitList app should pass the persistence test. Double-tap the Home button to bring up the fast app switcher. Terminate the HitList app by flicking it upwards.
From Springboard, tap the HitList app to trigger a fresh launch. Wait, what happened? The table view is empty:
You saved to Core Data, but after a fresh app launch, the people array is empty! That’s because the data is sitting on disk waiting for you, but you’re not showing it yet.
Fetching from Core Data
To get data from your persistent store into the managed object context, you have to fetch it. Open ViewController.swift and add this code below viewDidLoad():
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //1 guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext //2 let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person") //3 do { people = try managedContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } }
Step by step, this is what the code does:
Before you can do anything with Core Data, you need a managed object context. Fetching is no different! Like before, you pull up the application delegate and grab a reference to its persistent container to get your hands on its NSManagedObjectContext.
As the name suggests, NSFetchRequest is the class responsible for fetching from Core Data. Fetch requests are both powerful and flexible. You can use fetch requests to fetch a set of objects meeting the provided criteria (i.e. give me all employees living in Wisconsin and have been with the company at least three years), individual values (i.e. give me the longest name in the database) and more.
Fetch requests have several qualifiers used to refine the set of results returned. You’ll learn more about these qualifiers in Chapter 4, “Intermediate Fetching”; for now, you should know NSEntityDescription is a required one of these qualifiers.
Setting a fetch request’s entity property, or alternatively initializing it with init(entityName:), fetches all objects of a particular entity. This is what you do here to fetch all Person entities. Also note NSFetchRequest is a generic type. This use of generics specifies a fetch request’s expected return type, in this case NSManagedObject.
You hand the fetch request over to the managed object context to do the heavy lifting. fetch(_:) returns an array of managed objects meeting the criteria specified by the fetch request.
Note: Like save(), fetch(_:) can also throw an error so you have to use it within a do block. If an error occurred during the fetch, you can inspect the error inside the catch block and respond appropriately.
Build and run the application. Immediately, you should see the list of names you added earlier:
Great! They’re back from the dead (pun intended). Add a few more names to the list and restart the app to verify saving and fetching are working. Short of deleting the app, resetting the Simulator or throwing your phone off a tall building, the names will appear in the table view no matter what.
Where to Go From Here?
You can download the completed project for this tutorial here.
In just a few pages, you’ve already experienced several fundamental Core Data concepts: Data Models, entities, attributes, managed objects, managed object contexts and fetch requests.
If you enjoyed what you learned in this tutorial, why not check out the complete Core Data by Tutorials book, available in our store?
Here’s a taste of what’s in the book:
1. Chapter 1, Your First Core Data App: You’ll click File\New Project and write a Core Data app from scratch! This chapter covers the basics of setting up your data model and then adding and fetching records.
2. Chapter 2, NSManagedObject Subclasses: NSManagedObject is the base data storage class of your Core Data object graphs. This chapter will teach you how you customize your own managed object subclasses to store and validate data.
3. Chapter 3, The Core Data Stack: Under the hood, Core Data is made up of many parts working together. In this chapter, you’ll learn about how these parts fit together, and move away from the starter Xcode template to build your own customizable system.
4. Chapter 4, Intermediate Fetching: Your apps will fetch data all the time, and Core Data offers many options for getting the data to you efficiently. This chapter covers more advanced fetch requests, predicates, sorting and asynchronous fetching.
5. Chapter 5, NSFetchedResultsController: Table views are at the core of many iOS apps, and Apple wants to make Core Data play nicely with them! In this chapter, you’ll learn how NSFetchedResultsController can save you time and code when your table views are backed by data from Core Data.
6. Chapter 6, Versioning and Migration: As you update and enhance your app, its data model will almost certainly need to change. In this chapter, you’ll learn how to create multiple versions of your data model and then migrate your users forward so they can keep their existing data as they upgrade.
7. Chapter 7, Unit Tests: Testing is an important part of the development process, and you shouldn’t leave Core Data out of that! In this chapter, you’ll learn how to set up a separate test environment for Core Data and see examples of how to test your models.
8. Chapter 8, Measuring and Boosting Performance: No one ever complained that an app was too fast, so it’s important to be vigilant about tracking performance. In this chapter, you’ll learn how to measure your app’s performance with various Xcode tools and then pick up some tips for dealing with slow spots in your code.
9. Chapter 9, Multiple Managed Object Contexts: In this final chapter, you’ll expand the usual Core Data stack to include multiple managed object contexts. You’ll learn how this can improve perceived performance and help make your app architecture less monolithic and more compartmentalized.
And to help sweeten the deal, the digital edition of the book is on sale for $49.99! But don’t wait — this sale price is only available for a limited time.
Speaking of sweet deals, be sure to check out the great prizes we’re giving away this year with the iOS 11 Launch Party, including over $9,000 in giveaways!
To enter, simply retweet this post using the #ios11launchparty hashtag by using the button below:
Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
We hope you enjoy this update, and stay tuned for more book releases and updates!
The post Getting Started with Core Data Tutorial appeared first on Ray Wenderlich.
Getting Started with Core Data Tutorial published first on http://ift.tt/2fA8nUr
0 notes
mobilith · 7 years
Text
Storyboards Tutorial for iOS: Part 1
Storyboards, Scenes and View Controllers
Update note: This tutorial has been updated for Xcode 9, iOS 11, and Swift 4 by Nicholas Sakaimbo. The original tutorial was written by Matthijs Hollemans.
Storyboards are an exciting feature first introduced in iOS 5 that save time building user interfaces for your apps. Storyboards allow you to prototype and design multiple view controller views within one file.
Before Storyboards you had to use XIB files and you could only use one XIB file per view (UITableViewCell, UITableView or other supported UIView types).
The following image shows you what a storyboard looks like, and it’s similar to the storyboard you’ll build during this tutorial:
You may not know what the app does but you can see its scenes and how they’re related.
Storyboards have a number of advantages:
You can visually lay out all your view controllers in “scenes” and describe the connections between them. With a storyboard you’ve a better conceptual overview of all the scenes in your app.
Describe the transitions between the various scenes. These transitions are called “segues” and you create them by connecting your view controllers in the storyboard. Thanks to segues you need less code to take care of your UI.
Make working with table views a lot easier with prototype and static cells features. You can design your table views almost completely in the storyboard editor, cutting down the amount of code you have to write.
Make it easier to use Auto Layout, a feature that allows you to define mathematical relationships between elements defining their position and sizing. This powerful feature makes it easier to handle devices of varying screen sizes and dimensions. In this tutorial you’ll use Auto Layout a little, but it’s outside the scope of this tutorial. You can read more in our Auto Layout Tutorial or watch the video series.
In this tutorial you’re going to build a sample app to create a list of players and show you the games they play and their skill rating. In the process, you’ll learn common tasks which can be accomplished using in storyboards.
Getting Started
Open Xcode and create a new project. Use the Single View Application template as the starting point.
Fill in the template options as follows, click Next and then Create:
Product Name: Ratings
Organization Name: fill this in however you like
Organization Identifier: the identifier you use for your apps
Language: Swift
Make sure Use Core Data, Include Unit Tests and UI Tests are unchecked
Once created, the main Xcode window should look like the following:
The new project consists of three files, AppDelegate.swift, ViewController.swift, and the star of this tutorial: Main.storyboard.
Under Deployment Info > Device Orientation in the General project settings, set Devices to iPhone. Since this is a portrait-only app, uncheck the Landscape Left and Landscape Right options.
Open Main.storyboard in the project navigator to view it in the Interface Builder editor:
The official storyboard terminology for a view controller is “scene”, but you can use the terms interchangeably. A scene represents a view controller in the storyboard.
Here you see a single view controller containing an empty view. The arrow pointing to the view controller from the left indicates it’s the initial view controller to be displayed for this storyboard.
Designing a layout in the storyboard editor is done by dragging controls from the Object Library (see bottom-right corner) into your view controller.
You’ll notice the default scene size is for a 4.7-inch screen. Xcode enables Auto Layout and Size Classes by default for storyboards. Auto Layout and Size Classes allow you to make flexible user interfaces that can easily resize, which is useful for supporting the various sizes of iPhones and iPads. To change the scene size to another device, click the button at the bottom left of the storyboard. You’ll then be able to select from the full range of supported device sizes, ranging from the iPad Pro (12.9-inch) to the iPhone 4S (3.5-inch), in both portrait and landscape orientations.
For this tutorial, we’ll leave the default scene size – iPhone 7 – unchanged, so make sure to switch it back if you’ve toggled through a couple of different device sizes. Xcode will automatically re-size existing and new scenes added to the storyboard for the currently-selected device size.
To get a feel for how the storyboard editor works, drag some controls from the Object Library into the blank view controller:
As you drag controls in, they should show up in the Document Outline on the left:
The storyboard shows the contents of all your scenes. Currently there’s only one scene in your storyboard, but over the course of this tutorial you’ll add several others.
There’s a miniature version of this Document Outline above the scene called the Dock:
The Dock shows the top-level objects in the scene. Each scene has at least a View Controller object, a First Responder object, and an Exit object. It can potentially have other top-level objects as well. The Dock is convenient for making connections to outlets and actions. If you need to connect something to the scene, you can simply drag to its icon in the Dock.
Note: You probably won’t use the First Responder very much. This is a proxy object referring to whatever object has first responder status at any given time. As an example, you can hook up the Touch Up Inside event from a button to First Responder’s cut: selector. If at some point a text field has input focus then you can press that button to make the text field, which is now the first responder, cut its text to the pasteboard.
Build and run the app, it should look exactly like what you designed in the editor (yours may look different than the screenshot below):
The single view controller you defined was set as the Initial View Controller – but how did the app load it? Open AppDelegate.swift to find the answer:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true }
The @UIApplicationMain attribute at the top of the file designates the AppDelegate class as the entry point for the module. It’s a requirement for using storyboards your application delegate inherits from UIResponder and has a UIWindow property. All the methods are practically empty. Even application(_:didFinishLaunchingWithOptions:) simply returns true.
The secret’s in the Info.plist file. Open Info.plist in the Project Navigator and you’ll see the following:
Storyboard apps use the UIMainStoryboardFile key, also known as “Main storyboard file base name”, to specify the name of the storyboard to load when the app starts. When this setting is present, UIApplication will load the named storyboard file, automatically instantiate the “Initial View Controller”, and put that controller’s view into a new UIWindow object.
You can also see this in the Project Settings under the General tab and Deployment Info section:
Now to create the real Ratings app with several view controllers.
Just Add It To My Tab
The Ratings app you’re about to build has a tabbed interface with two scenes. With a storyboard it’s easy to create tabs.
Open Main.storyboard and delete the scene you worked with earlier. This can be done by clicking on View Controller in the Document Outline and pressing the delete key.
Drag a Tab Bar Controller from the Object Library into the canvas. You may want to maximize your Xcode window first, because the Tab Bar Controller comes with two view controllers attached and you’ll need some room to maneuver. You can zoom in and out by double-clicking the canvas, or set the zoom scale by ctrl-clicking the canvas and selecting the zoom level.
The new Tab Bar Controller comes pre-configured with two additional view controllers – one for each tab. UITabBarController is a so-called container view controller because it contains one or more other view controllers. Two other common containers are Navigation Controller and Split View Controller (you’ll use the Navigation Controller later).
The container Relationship is represented by the arrows between the Tab Bar Controller and the view controllers it contains. An embed Relationship in particular is signified by the icon seen below in the middle of the arrow body.
Note: If you want to move the Tab Bar Controller and its attached view controllers as a group, zoom out, then ⌘-click or click and drag to select multiple scenes. This makes it possible to move them around together. (Selected scenes have a thin blue outline.)
Drag a label into the first view controller (currently titled “Item 1”), double click it, and give it the text “First Tab”. Next, drag a label into the second view controller (“Item 2”) and give it the text “Second Tab”. This allows you to see something happen when you switch between the tabs.
Build and run the app. You’ll see something similar to this in the console:
Ratings[18955:1293100] Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?
Fortunately, the error is pretty clear here – you never set an entry point, meaning you didn’t set the Initial View Controller after you deleted the previous scene. To fix this, select the Tab Bar Controller, go to the Attributes Inspector and check Is Initial View Controller.
In the canvas, an arrow now points at the Tab Bar Controller:
Now when you run the app, UIApplication will make the Tab Bar Controller the main screen. Build and run the app. Now you can see a tab bar and can switch between the two view controllers:
Note: To change the initial view controller, you can also drag the arrow between view controllers.
Xcode comes with a template for building a tabbed app (called the Tabbed Application template). You could have used it, but it’s good to know how this works so you can create a Tab Bar Controller by hand if you have to.
Note: If you connect more than five scenes to the Tab Bar Controller, it automatically gets a More… tab when you run the app. Pretty neat!
Adding a Table View Controller
The two scenes currently attached to the Tab Bar Controller are both UIViewController instances. You’re going to replace first tab scene with a UITableViewController instead.
Click on the first view controller in the Document Outline to select it, then delete it. Drag a new Table View Controller into the canvas where the previous scene used to be:
Next, you want to place the Table View Controller inside a navigation controller. First, select the Table View Controller. Next, choose Editor\Embed In\Navigation Controller from Xcode’s menubar. This adds another controller to the canvas:
You could have dragged in a Navigation Controller from the Object Library and embedded the table view, but this Embed In command is a nice time saver for a common action.
Since the Navigation Controller is also a container view controller (just like the Tab Bar Controller), it has a relationship arrow pointing to the Table View Controller. You can also see these relationships in the Document Outline:
Notice embedding the Table View Controller gave it a navigation bar. Interface Builder automatically put it there because this scene will now be displayed inside the Navigation Controller’s frame. It’s not a real UINavigationBar object, but a simulated one. Simulated Metrics will infer the context around the scene and show a navigation bar when it’s inside a Navigation Controller, a tab bar when it’s inside a Tab Bar Controller, and so on.
To connect these two new scenes to the Tab Bar Controller, ctrl-drag from the Tab Bar Controller to the Navigation Controller. When you let go, a small popup menu appears. Choose the Relationship Segue – view controllers option:
This creates a new relationship arrow between the two scenes. This is also an embed Relationship as you saw with the other controllers contained by the Tab Bar Controller.
The Tab Bar Controller has two embed relationships, one for each tab. The Navigation Controller itself has an embed Relationship with the Table View Controller.
When you made this new connection, a new tab was added to the Tab Bar Controller, simply named “Item”. For this app, you want this new scene to be the first tab, so drag the tabs around to change their order:
Build and run the app to try it out. The first tab now contains a table view inside a navigation controller.
Before you put some actual functionality into this app, you need to clean up the storyboard a little. You’ll name the first tab “Players” and the second “Gestures”. You don’t change this on the Tab Bar Controller itself, but in the view controllers connected to these tabs.
As soon as you connect a view controller to a Tab Bar Controller, it’s given a Tab Bar Item object which you can see in the Document Outline or the bottom of the scene. Use this Tab Bar Item to configure the tab’s title and image seen on the Tab Bar Controller.
Select the Tab Bar Item inside the Navigation Controller, and in the Attributes inspector set its Title to Players:
Next, rename the Tab Bar Item for the second tab to Gestures the same way you did above.
A well-designed app should also put icons on these tabs. The resources for this tutorial contains a subfolder named Images. Drag that folder into the Assets.xcassets subfolder in the project.
Open Main.storyboard, in the Attributes inspector for the Players Tab Bar Item, choose the Players image.
Next, give the Gestures Tab Bar Item the image Gestures.
A view controller embedded inside a Navigation Controller has a Navigation Item used to configure the navigation bar. Select the Navigation Item for the Table View Controller in the Document Outline and change its title in the Attributes inspector to Players. .
Notice the Scene title in the Document Outline now changes to Players
Note: Alternatively, you can double-click the navigation bar and change the title there. You should double-click the simulated navigation bar in the Table View Controller, not the actual Navigation Bar object in the Navigation Controller.
Build and run the app. Now marvel at your pretty tab bar, created without writing a single line of code!
Prototype Cells
Prototype cells allow you to easily design a custom layout for your table view cells directly within the storyboard editor.
The Table View Controller comes with a blank prototype cell. Click the cell to select it and in the Attributes inspector set the Style option to Subtitle. This immediately changes the appearance of the cell to include two labels.
Note: With so much stackable content on a storyboard, it can sometimes be difficult to click on exactly what you want. If you have trouble, there’s several options. One is you can select the item in the Document Outline to the left of the canvas. The second is a handy hotkey: hold control + shift and click on the area you’re interested in. A popup will appear allowing you to select any element directly under your cursor.
If you’ve used table views before and created your own cells by hand, you may recognize this as the UITableViewCellStyle.Subtitle style. With prototype cells you can pick one of the built-in cell styles as you just did, or create your own custom design (which you’ll do shortly).
Set the Accessory attribute to Disclosure Indicator and the Identifier to PlayerCell. All prototype cells must have a reuse identifier so you can refer to them in code. In addition, set the cell’s Selection to None.
Note: The cell’s Selection attribute is set to None to prevent the user from editing an existing item by tapping the PlayerCell. Although you won’t be adding this functionality in this tutorial, you will have enough knowledge by the end of Part 2 to implement this feature into the sample project for additional practice.
Build and run the app, nothing has changed. That’s not so strange: you still have to make a data source for the table so it knows which rows to display. You’re going to do that next.
Add a new file to the project. Choose the Cocoa Touch Class template under iOS/Source. Name the class PlayersViewController and make it a subclass of UITableViewController. Uncheck Also create XIB file. Choose the Swift language and hit Next followed by Create.
Open Main.storyboard and select the Table View Controller (make sure you select the actual view controller and not one of its views). In the Identity inspector, set its Class to PlayersViewController. This is an essential step for hooking up a scene from the storyboard with your custom view controller subclass. Don’t forget this or your class won’t be used!
Now when you run the app the table view controller from the storyboard is an instance of the PlayersViewController class.
The table view should display a list of players, so now you’ll create the main data model for the app – an array containing Player objects. Add a new file to the project using the Swift File template under iOS/Source and name the file Player.
Replace the code in Player.swift with the following:
import Foundation struct Player { // MARK: - Properties var name: String? var game: String? var rating: Int }
There’s nothing special going on here. Player is simply a container object for these three properties: the name of the player, the game they’re playing, and a rating of 1 to 5 stars. Note because you didn’t define a custom initializer, the struct will automatically receive a default memberwise initializer which can be used to set all of its properties.
Next, create a new file using the Swift File template named SampleData. Replace the contents of SampleData.swift with the following:
import Foundation final class SampleData { static func generatePlayersData() -> [Player] { return [ Player(name: "Bill Evans", game: "Tic-Tac-Toe", rating: 4), Player(name: "Oscar Peterson", game: "Spin the Bottle", rating: 5), Player(name: "Dave Brubeck", game: "Texas Hold 'em Poker", rating: 2) ] } }
Here you’ve defined a static method on SampleData to generate an array of hard coded Player objects.
Next, open PlayersViewController.swift and replace the contents of the file with the following:
import UIKit class PlayersViewController: UITableViewController { // MARK: - Properties var players = SampleData.generatePlayersData() }
You could have set up the sample data in PlayersViewController when defining the players variable. But this data might be provided from a plist or other outside source, hence it’s wise to handle loading the data outside of the view controller.
Now you’ve an array full of Player objects, continue hooking up the data source in PlayersViewController. Still in PlayersViewController.swift, add the following extension to the end of the file:
// MARK: - UITableViewDataSource extension PlayersViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return players.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) let player = players[indexPath.row] cell.textLabel?.text = player.name cell.detailTextLabel?.text = player.game return cell } }
The method dequeueReusableCell(withIdentifier:for:) will check to see if there’s an existing cell that can be recycled. If not, it will automatically allocate a prototype cell and return it to you. All you need to do is supply the re-use identifier you set on the prototype cell in the storyboard editor – in this case PlayerCell. Don’t forget to set the identifier, or this little scheme won’t work!
Build and run the app, the table view has players in it!
It takes just a few lines of code to use these prototype cells. I think that’s just great!
Note: In this app you’re using only one prototype cell. If your table needs to display different kinds of cells you can add additional prototype cells to the storyboard. Make sure to give each cell its own re-use identifier!
Designing Your Own Prototype Cells
Using a standard cell style is fine for most apps, but for this app you want to add an image on the right-hand side of the cell showing the player’s rating. Having an image view in that spot is not supported by the standard cell styles, so you’ll have to make a custom design.
Open Main.storyboard, select the prototype cell in the table view, and in Attributes inspector, set its Style attribute to Custom. The default labels now disappear.
First make the cell a little taller. Either change the Row Height value in the Size inspector (after checking Custom) or drag the handle at the bottom of the cell. Make the cell 60 points high.
Drag two Label objects from the Objects Library into the cell and place them roughly where the standard labels were previously. Just play with the font and colors in the Attributes Inspector and pick something you like. Set the text of the top label to Name and the bottom label to Game.
Select both the Name and Game labels in the Document Outline using Command+click, and choose Editor\Embed In\Stack View.
Note: Stack views were introduced in in iOS 9 and are brilliant for easily laying out collections of views. You can find out more about stack views in our UIStackView Tutorial.
Drag an Image View into the cell and place it on the right, next to the disclosure indicator. In the Size Inspector, make it 81 points wide and 35 points high. Set its Content Mode to Center (under View in the Attributes inspector) so whatever image you put into this view is not stretched.
Command + click the Stack View and Image View in the Document Outline to select both of them. Choose Editor\Embed in\Stack View. Xcode will create a new horizontal stack view containing these two controls.
Select this new horizontal stack view, and in the Attributes Inspector, change the Alignment to Center and the Distribution to Equal Spacing.
Now for some simple auto layout for this control. At the bottom right of the storyboard, click the Pin icon:
Change the top constraints to Top: 0, Right: 20, Bottom: 0 and Left: 20. Make sure the four red pointers to the values are highlighted as in the picture. Click Add 4 Constraints at the bottom of the popover window.
If your stack view has orange constraints, it is misplaced. To fix this, select the horizontal stack view and choose Editor\Resolve Auto Layout Issues\Update Frames (in the Selected Views section of the menu). The stack view should position itself correctly and the orange constraint errors go away.
To position the image view within the stack view, select the image view in the Document Outline and choose Editor\Resolve Auto Layout Issues\Add Missing Constraints (in the Selected Views section of the menu).
You may see a small arrow highlighted in red in the Document Outline indicating unresolved layout issues with the stack view. Click on this arrow and click on the red circle to view Xcode’s suggested auto-fix. Selecting Change Priority for either the Name or Game labels’ hugging priority should silence this warning.
The final design for the prototype cell looks something like this:
Because this is a custom designed cell, you can no longer use UITableViewCell’s textLabel and detailTextLabel properties to put text into the labels. These properties refer to labels that aren’t on this cell anymore; they’re only valid for the standard cell types. Instead, you’ll subclass UITableViewCell to provide the functionality.
Note: You could use Tags in this situation, however tags do not provide the type of object which the compiler can check at runtime hence you have to use type casting and checking during runtime which you should avoid if at all possible. For this reason, tags were no longer considered prudent to teach in this situation.
Using a Subclass for the Cell
Add a new file to the project, with the Cocoa Touch Class template. Name it PlayerCell and make it a subclass of UITableViewCell. Don’t check the option to create a XIB, as you already have the cell in your storyboard.
Next, add the following to the PlayerCell class, just below the class definition:
// MARK: - IBOutlets @IBOutlet weak var gameLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var ratingImageView: UIImageView!
These IBOutlets can be connected to your scene using the storyboard.
Next, add the following property below the IBOutlets:
// MARK: - Properties var player: Player? { didSet { guard let player = player else { return } gameLabel.text = player.game nameLabel.text = player.name ratingImageView.image = image(forRating: player.rating) } }
Whenever the player property is set, it’ll verify there’s a value and if so, update the IBOutlets with the correct information.
Next, add the following method below player:
func image(forRating rating: Int) -> UIImage? { let imageName = "\(rating)Stars" return UIImage(named: imageName) }
This returns a different star image depending on the provided rating.
Next, open Main.storyboard, select the prototype cell PlayerCell and change its class to PlayerCell in the Identity inspector. Now whenever you ask the table view for a new cell with dequeueReusableCell(withIdentifier:for:), it’ll return a PlayerCell instance instead of a regular UITableViewCell.
Note: You gave this class the same name as the reuse identifier – they’re both called PlayerCell – but that’s only because I like to keep things consistent. The class name and reuse identifier have nothing to do with each other, so you can name them differently if you wish.
Finally, connect the labels and the image view to these outlets. Navigate to the Connections Inspector in the storyboard and then select the Player Cell from either the canvas or Document Outline. Drag from the nameLabel Outlet in the Connections inspector to the Name label object in either the Document Outline, or the canvas. Repeat for gameLabel and ratingImageView.
Note: You should hook up the controls to the table view cell, not to the view controller! You see, whenever your data source asks the table view for a new cell with dequeueReusableCell, the table view doesn’t give you the actual prototype cell but a copy (or one of the previous cells is recycled if possible).
This means there will be more than one instance of PlayerCell at any given time. If you were to connect a label from the cell to an outlet on the view controller, then several copies of the label will try to use the same outlet. That’s just asking for trouble. (On the other hand, connecting the prototype cell to actions on the view controller is perfectly fine. You would do that if you’ve custom buttons or other UIControls on your cell.)
Now you’ve hooked up the properties, you can simplify the data source code a bit. Open PlayersViewController.swift, and change tableView(_:cellForRowAt:) to the following:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as! PlayerCell let player = players[indexPath.row] cell.player = player return cell }
That’s more like it. You now cast the object you receive from dequeueReusableCell to a PlayerCell, and pass the correct player to the cell. Setting the player variable in PlayerCell will automatically propagate the values into the labels and image view. Isn’t it great how using prototype cells makes table views a whole lot less messy?
Build and run the app.
Hmm, that doesn’t look quite right – the cells appear to be squished. You did change the height of the prototype cell, but the table view doesn’t take that into consideration. There’s two ways to fix it: you can change the table view’s Row Height attribute, or implement the tableView(_:heightForRowAt:) method. The former is fine in this case because we only have one type of cell and we know the height in advance.
Note: You would use tableView(_:heightForRowAt:) if you didn’t know the height of your cells in advance, or if different rows can have different heights.
Open Main.storyboard, in the Size inspector of the Table View, set Row Height to 60:
Build an run the app.
That’s much better isn’t it!
Note: If you changed the cell height by dragging its handle rather than typing in the value, the table view’s Row Height property was automatically changed too. So it may have worked correctly for you the first time around.
Where To Go From Here?
Click here to download the full source code for the project up to this point.
Check out part two of this tutorial, where we’ll cover segues, static table view cells, the Add Player scene, a game picker scene, and the full downloadable example project for this tutorial!
If you felt lost at any point during this tutorial, you also might want to brush up on the basics with our iOS Apprentice series. In that series, you’ll learn the foundational knowledge you need as an iOS developer from the ground up — perfect for complete beginners, or those looking to fill in some gaps.
If you have any questions or comments on this tutorial or on storyboards, please join the forum discussion below!
The post Storyboards Tutorial for iOS: Part 1 appeared first on Ray Wenderlich.
Storyboards Tutorial for iOS: Part 1 syndicated from http://ift.tt/2uHrXAJ
0 notes