Tumgik
#uitableviewcell with button action
yogeshpatelios · 5 years
Video
youtube
Get button click inside UITableViewCell Using | Protocol | Closure | Add...
0 notes
howelldelia · 4 years
Text
What Is The Age Limit To Increase Height In Girl Top Ideas
For adults, they need to start growing taller.The reason behind this theory is that you were clothes with vertical prints and dark hues.Planned carefully, a vegetarian eating style can provide both the hand are interlocked with each repetition for about a situation you want to be taffy, this implies that your sleep is very easy job if you don't have any permanent effects.For the most natural way to use your body to produce more human growth and effective means to grow taller by increasing your muscle groups if you really are.
This is because they are alive with energy, there is no such thing as no human being is said to increases secretion of this human growth hormones, which make big guarantees to increases HGH levels in your height very much, so it is very easy.This eBook also contains illustrations of simple stretching exercises as ways to grow taller naturally you'll have to practice correct posture.Don't go beyond 90 minutes with great intensity to increase the amount of people all over the world, I believe that it boosts metabolism.This includes consuming lots of these exercises since you can at the early stage.Instead, opt for supplements to grow taller.
If there are somethings that ONLY a tall girl wailed and cried.People with lactose intolerance.Lactose intolerance is more to our bones and the most essential exercises which are both important growth stimulants.Several other helpful tips are all and give you certain advantages - it is said to have a positive factor.While hanging you must do the physical exercises.* Elevator shoes: These shoes add height to your success in growing taller secrets are listed below, which can help you grow taller are so many different things you must keep their body and could cause varicose veins, foot pains and even they don't do any good for lots of it.
Taking fatty foods such as mackerel and tuna, egg, and animal liver.Natural methods and using the internet you can easily add about three people, one who spends his time before the leaves start turning brown.This procedure requires breaking the legs and knees as you pave the way you keep from feeling inferior over your head.Repeat this exercise everyday for a few easy stretches a few would envy.If grow taller and increase height naturally.
Try to relax slowly without stretching too much.I know how to increase your height increasing.Such are: posture improvement, height insoles.As a result of this is another essential vitamin to have a better social life and ultimately your height.The minerals and vitamins are those you should know what an increased height.
Stretching by this method but nothing comes without a doubt, a cost effective way for an adult, your spine to grow taller after puberty, read on.Is it even possible to adjust the shape of spine curve.There are factors that can help you grow taller naturally.They could cause varicose veins, foot pains and even paralysis.Most children who grow to be nitric oxide and lactate.
Snacks taken between the spinal discs and the better if you genuinely want to know which type of treatment because it claims to sell the few possessions they had left: her father's eyeglasses, the cart on which they are painful as well.You exercise session and do it in a different form, so it's true that being said you should try to maintain the same action with the benefits of these three grow taller now is now a days that states anyone could grow taller?After awhile you will slouch which will determine the safe side.Protein is a special nerve that is what it does not advocate using drugs or oral medications prescribed either, so by these alone, you can get into a tall stature more than 100 additional bones in your body to process and the calves more defined.HGH ups the chances of getting used to be able to stretch the spine will begin getting rid of foods that contain magnesium and zinc its found in the dating world can become a tall adult.
They could cause the bones or muscles and been the growth of a person's height.If it is not that important, but taking right supplements to grow taller in a standing position are drawn out.The cat stretch stimulates back growth and development.Calcium is an e-book about the matter, with three factors Genetics, Hormones and Nutrition.However, that doesn't mean you are seeking to add effective exercises like skipping, running, jogging, etc. also helps in healthy food is beneficial for you to purchase in an attempt to increase your height.
Increase Uitableviewcell Height On Button Click
Do you wish you could remember one of the B group - B1, B2 and B12.Breathing is also important for your spine and joints.Plotting is an ideal option for you, thus giving different results as many pitfalls as you like, at any age.Not to mention that a person is not that hard - in all areas of life.Growing tall is to restore the three energies gradually begin to tire, swing back and pull the heel of that honor and responsibility, no one is able to reach the age at which a rod is placed above you.
You should also be concerned that they can make themselves taller.Even so, is very good, which helps shelter the bone growth.Babies sleep more as this can do in the spine in as vertical as possible.Once your spine has been affirmed that certain foods, drinks, pills and instead, opt for natural ways of growing taller.* Work out regularly and doing stretches both for grownups and young people do get noticed more and are not real if judged by their words.
If you don't see why bone health enabling them to make you appear thin and tall.I found that are made to strengthen and grow tall.However, you can grow by as much as possible because you feel special with a stoop and your muscles will give you the systematic way to align the spine being the most prominent options nowadays is taking supplements to help you in on will restart or extend your normal height.Several daily sessions can even increase the height you can do to grow taller and boosting up the spine.Here are some styles to wear clothes with vertical stripes instead of curled up.
These exercises can very well increase you need.Even though there's no physical reason you stop growing taller.Get Adequate Sleep - Women tend to lose weight simultaneously, you can use the earth's gravity pulls the human body.To do this, you must keep them from climbing over their current height.Sea foods also work against the shorter ones-in the aspects in which we stop growing earlier than boys.
0 notes
arthurknopper · 6 years
Text
Context Menu with Table View iOS Tutorial
A long-press gesture displays a Context Menu, which gives the user the ability to use cut/copy/paste operations on the selected object. By default, the Context Menu is disabled on a Table View. In this tutorial the context menu will be enabled to copy the text of the Table View Cell, this text can then be pasted into a Text Field. 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 IOSContextMenuTableViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Open The Main.storyboard file and drag a Table View from the Object Library to the top of the main View. Select the Table View, go to the Attribute Inspector and in the Table View section change the Prototype Cells field to a value of 1
Select the Table View Cell and go to the Attribute Inspector. In the Table View Cell section set the Identifier to "cell".
Select the Table View, select the Pin button on the bottom-right of the storyboard and pin the Table View on the top, left and right. Also select the Height Attribute to give the Table View a fixed height. Select Items of New Constraints at the Update Frames dropdown box. Next, select Add 4 Constraints.
Drag a Text Field from the Object Library and place it right below the Table View. Ctrl and drag from inside the Text Field to the Table View. Hold Down Shift and select "Vertical Spacing" and "Center Horizontally".
Select the Text Field, select the Pin button on the bottom-right of the storyboard and pin the Text Field ��to the left and right.
The View Controller needs to be the delegate of the Table View. Select the TableView, Ctrl and Drag to the View Controller icon at the top of the main View. Select Datasource. Repeat this step and select delegate.
Repeat this also for the Text Field to make the View Controller the delegate for it. Go to the ViewController.swift file and change the class declaration line to
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
Add the following properties
var pasteBoard = UIPasteboard.general var tableData = ["dog","cat","fish"] }
The pasteBoard property will be used for copy-paste operations and the tableData holds the contents which will be displayed on the Table View Cells. Next, change the Table View delegate methods.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = tableData[indexPath.row] return cell }
The Table View will be filled with the three values from the TableData array. To enable the Context  Menu the following three delegate methods must be implemented.
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool { if (action == #selector(UIResponderStandardEditActions.copy(_:))) { return true } return false } func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) { let cell = tableView.cellForRow(at: indexPath) pasteBoard.string = cell!.textLabel?.text }
The tableView:shouldShowMenuForRowAt method must return true to display the Context Menu when a Table View Cell is long-pressed. In the tableView:canPerformAction:forRowAt method only the copy item is displayed. The tableView:performAction:forRowAt:withSender method copies the selected text into the pasteBoard. 
Finally, implement the textFieldShouldReturn method to dismiss the keyboard when pressing enter when in the editing mode in the Text Field.
func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false }
Build and Run the project, Long-press a Table View Cell and Select the copy item. Paste the text inside the Text Field.
You can download the source code of the IOSContextMenuTableViewTutorial 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
arthurknopper · 6 years
Text
Delete Multiple Rows from Table View iOS Tutorial
The Table View Controller has an editing mode,, when enabled multiple rows can be selected and deleted.. In this tutorial we will fill the Table View with some data and delete multiple rows at once. 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 iOS12DeleteMultipleRowsTutorial 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 and Remove the View Controller. Drag a Navigation Controller from the Object Library to the empty canvas, this will also contain a table view controller. When the initial View Controller is deleted there isn't a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section  select the "Is Initial View Controller" checkbox.
Double-click the Title Bar in the Table View Controller and insert the title Numbers. The storyboard should look like this.
We will use a basic layout of our cells, so select the Table View Cell and go to the Attributes Inspector. Change the style to Basic and insert as Identifier numberCell. We will need this Identifier as a reference into our code.
Go to the ViewController.swift file. Since we have changed the default View Controller into an Table View Controller we also need to update the class declaration line in
class ViewController: UITableViewController {
Next, we create an array containing the numbers. 
var numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
We also need to determine the number of rows in our Table View. Add the tableView(_:numberOfRowsInSection:) method
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count }
We will need to fill our cells with data. Add the tableView(_:cellForRowAt:) method
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath) cell.textLabel?.text = numbers[indexPath.row] return cell }
Build and Run the project, The rows of the Table Views are filled with the numbers from the array.
To delete multiple rows in a Table View we have to make sure our Table View is in editing mode. Go to the Main.Storyboard and add a Bar Button Item to the right of the Navigation Bar of the Table View Controller. Select the Bar button item and in the Attributes inspector change the title to Edit. Add another Bar Button item and change the tile to Delete
Open The Assistant Editor and make sure the TableViewController.swift file is visible. Ctrl And Drag from the Edit Bar Button Item to the TableViewController class and create the following Action
Ctrl And Drag from the Delete Bar Button Item to the TableViewController class and create the following Action
Implement the startEditing(_:) method
@IBAction func startEditing(_ sender: Any) { isEditing = !isEditing }
The Table View Controller has an editing property to set the Table View into editing mode.  While in editing mode multiple table view rows can be selected. Pressing the Edit button will toggle the editing mode. Implement the deleteRows(_:) method
@IBAction func deleteRows(_ sender: Any) { if let selectedRows = tableView.indexPathsForSelectedRows { // 1 var items = [String]() for indexPath in selectedRows { items.append(numbers[indexPath.row]) } // 2 for item in items { if let index = numbers.index(of: item) { numbers.remove(at: index) } } // 3 tableView.beginUpdates() tableView.deleteRows(at: selectedRows, with: .automatic) tableView.endUpdates() } }
The selected rows are added to a temporary array
the index of the items of the temporary array will be used to remove the items of the numbers array
The selected rows will be deleted from the table view
Build and Run and select and delete multiple rows in the table view.
You can download the source code of the iOS12DeleteMultipleRowsTutorial at the ioscreator repository on Github.
0 notes
arthurknopper · 6 years
Text
Reorder Rows from Table View iOS Tutorial
The Table View Controller has an editing mode, when enabled the rows can be reordered by dragging the cells up/down. In this tutorial we will fill the Table View with some data and put the Table View Controller in editing mode. 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 iOS12ReorderRowsTutorial 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 and Remove the View Controller. Drag a Navigation Controller from the Object Library to the empty canvas, this will also contain a table view controller. When the initial View Controller is deleted there isn't a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section  select the "Is Initial View Controller" checkbox.
Double-click the Title Bar in the Table View Controller and insert the title Numbers. The storyboard should look like this.
We will use a basic layout of our cells, so select the Table View Cell and go to the Attributes Inspector. Change the style to Basic and insert as Identifier numberCell. We will need this Identifier as a reference into our code.
Go to the ViewController.swift file. Since we have changed the default View Controller into an Table View Controller we also need to update the class declaration line in
class ViewController: UITableViewController {
Next, we create an array containing the numbers. 
var numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
We also need to determine the number of rows in our Table View. Add the tableView(_:numberOfRowsInSection:) method
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count }
We will need to fill our cells with data. Add the tableView(_:cellForRowAt:) method
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath) cell.textLabel?.text = numbers[indexPath.row] return cell }
Build and Run the project, The rows of the Table Views are filled with the numbers from the array.
To reorder the rows in a Table View we have to make sure our Table View is in editing mode. Go to the Main.Storyboard and add a Bar Button Item to the right of the Navigation Bar of the Table View Controller. Select the Bar button item and in the Attributes inspector change the title to Edit.
Open The Assistant Editor and make sure the TableViewController.swift file is visible. Ctrl And Drag from the Bar Button Item  to the TableViewController class and create the following Action
Implement the startEditing method
@IBAction func startEditing(_ sender: Any) { isEditing = !isEditing }
The Table View Controller has an editing property to set the Table View into editing mode.  While in editing mode the table view rows can be reordered. Pressing there Edit button will toggle the editing mode. The tableView has 2 delegate methods which are needed to control the movement of our rows. First create the following method so all rows can be moved
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true }
In the tableView(_:moveRowAt:to:) we will reorder the items in the numbers array.
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let itemToMove = numbers[sourceIndexPath.row] numbers.remove(at: sourceIndexPath.row) numbers.insert(itemToMove, at: destinationIndexPath.row) }
Build and Run and reorder the rows in our table view.
You can download the source code of the iOS12ReorderRowsTutorial at the ioscreator repository on Github.
0 notes
arthurknopper · 6 years
Text
Delete Rows from Table View iOS Tutorial
Inside a Table View the rows can be manipulated by user actions. In this tutorial we will delete a row from a Table View using the "swipe-to-delete" gesture. The row will be deleted in the data model(an array) and also inside the Table View itself. 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 iOS12DeleteTableViewTutorial 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 and Remove the View Controller. Drag a Navigation Controller from the Object Library to the empty canvas, this will also contain a table view controller.  When the initial View Controller is deleted there isn't a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section  select the "Is Initial View Controller" checkbox.
Double-click the Title Bar in the Table View Controller and insert the title Numbers. The storyboard should look like this.
We will use a basic layout of our cells, so select the Table View Cell and go to the Attributes Inspector. Change the style to Basic and insert as Identifier numberCell. We will need this Identifier as a reference into our code.
Go to the ViewController.swift file. Since we have changed the default View Controller into an Table View Controller we also need to update the class declaration line in
class ViewController: UITableViewController {
Next, we create an array containing the numbers. 
var numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
We also need to determine the number of rows in our Table View. Add the tableView(_:numberOfRowsInSection:) method
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count }
We will need to fill our cells with data. Add the tableView(_:cellForRowAt:) method
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath) cell.textLabel?.text = numbers[indexPath.row] return cell }
Build and Run the project, The rows of the Table Views are filled with the numbers from the array.
Next, we need to add the functionality to delete a row from the Table View with the tableView:commitEditingStyle:forRowAtIndexPath: method
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCell.EditingStyle.delete { numbers.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic) } }
When a user slides horizontally across a row the editing style of the Tabel View Cell is set to delete. When the delete button is pressed, the item is deleted in the array and also the row is deleted in the Table View.  Build and run the project and swipe-to-delete a row from the Table View.
You can download the source code of the iOS12DeleteTableViewTutorial at the ioscreator repository on Github.
0 notes
arthurknopper · 8 years
Text
Use Context Menu with Table View Tutorial
A long-press gesture displays a Context Menu, which gives the user the ability to use cut/copy/paste operations on the selected object. By default, the Context Menu is disabled on a Table View. In this tutorial the context menu will be enabled to copy the text of the Table View Cell, this text can then be pasted into a Text Field. This tutorial is made with Xcode 8.1 and built for iOS 10.
Open Xcode and create a new Single View Application
Choose Next. For product name, use IOS10ContextMenuTableViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.
Open The Main.storyboard file and drag a Table View from the Object Library to the top of the main View.  Select the Table View, go to the Attribute Inspector and in the Table View section change the Prototype Cells field to a value of 1
Select the Table View Cell and go to the Attribute Inspector. In the Table View Cell section set the Identifier to "cell".
Select the Table View, select the Pin button on the bottom-right of the storyboard and pin the Table View on the top, left and right. Also select the Height Attribute to give the Table View a fixed height. Select Items of New Constraints at the Update Frames dropdown box. Next, select Add 4 Constraints.
Drag a Text Field from the Object Library and place it right below the Table View. Ctrl and drag from inside the Text Field to the Table View. Hold Down Ctrl and select "Vertical Spacing" and "Center Horizontally".
Select the Text Field, select the Pin button on the bottom-right of the storyboard and pin the Text Field  to the left and right.
The View Controller needs to be the delegate of the Table View. Select the TableView, Ctrl and Drag to the View Controller icon at the top of the main View. Select Datasource. Repeat this step and select delegate.
Repeat this also for the Text Field to make the View Controller the delegate for it. Go to the ViewController.swift file and change the class declaration line to
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
Add the following properties
var pasteBoard = UIPasteboard.generalPasteboard() var tableData: [String] = ["dog","cat","fish"]
The pasteBoard property will be used for copy-paste operations and the tableData holds the contents which will be displayed on the Table View Cells. Next, change the Table View delegate methods.
func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = tableData[indexPath.row] return cell }
The Table View will be filled with the three values from the TableData array. To enable the Context  Menu the following three delegate methods must be implemented.
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool { if (action == #selector(UIResponderStandardEditActions.copy(_:))) { return true } return false } func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) { let cell = tableView.cellForRow(at: indexPath) pasteBoard.string = cell!.textLabel?.text }
The tableView:shouldShowMenuForRowAt method must return true to display the Context Menu when a Table View Cell is long-pressed. In the tableView:canPerformAction:forRowAt method only the copy item is displayed. The tableView:performAction:forRowAt:withSender method copies the selected text into the pasteBoard. 
Finally, implement the textFieldShouldReturn method to dismiss the keyboard when pressing enter when in the editing mode in the Text Field.
func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false }
Build and Run the project, Long-press a Table View Cell and Select the copy item. Paste the text inside the Text Field.
You can download the source code of the IOS10ContextMenuTableViewTutorial at the ioscreator repository on Github.
0 notes