App development

iOS Storyboards: Segues and Extra [FREE]

Replace be aware: Ehab Yosry Amer up to date this tutorial for iOS 13, Xcode 11 and Swift 5. Nicholas Sakaimbo wrote the unique.

Within the earlier tutorial — iOS Storyboards: Getting Began — you realized easy methods to construct an app prototype utilizing solely storyboards. Your prototype had all of the screens and included navigation and circulate. On this tutorial, you’ll construct full performance and convert that prototype to a whole app.

Getting Began

Use the Obtain Supplies button on the prime or backside of this tutorial to obtain the starter undertaking. It has the storyboard you finalized within the earlier half, and some Swift recordsdata containing among the app’s logic, however no code is related to the storyboard but. That’s what you’ll do now. :]

The Mission navigator of your starter undertaking seems like this:

Alongside the best way, you’ll create new view controllers and join them to the prevailing storyboard. Time to get began.

Bringing the Gamers Display screen to Life

Open Essential.storyboard to try all of the scenes constructed within the earlier half. The primary display screen you’ll give life to is the Gamers Scene, which has a desk view. It was setup to make use of static cells and it already contains three cells.

To start out, right-click on the View Controllers folder and choose New File

New File Menu

Choose Swift File and title it PlayersViewController.swift.

PlayersViewController

The one code included within the file is an import assertion:

import Basis

It imports the Basis framework which incorporates primary lessons like String and Date. Substitute it with this as a substitute.

import UIKit

This imports the entire UIKit framework as a substitute, which is determined by Basis, so you should utilize lessons declared in each.

To outline your first scene, add the next to PlayersViewController.swift, after the import assertion:

class PlayersViewController: UITableViewController

You’ve gotten outlined a brand new class named PlayersViewController, and it’s a subclass of UITableViewController. You additionally outlined the property playersDataSource, which is an occasion of PlayersDataSource. This property offers the checklist of gamers so you may deal with exhibiting them within the desk view and never fear about how they’re saved and loaded.

This view controller is a subclass of UITableViewController, as a result of the scene on the storyboard is a desk view.

Storyboard PlayersViewController class

Observe: UITableViewController is a subclass of UIViewController, however the principle view on this scene is a UITableView. So, on this case, it’s extra handy to utilizing a desk view controller immediately.

Now, use the brand new class within the storyboard.

Storyboard, Please Meet My New Class

Open Essential.storyboard. Choose the Participant Scene that has a desk view within the Doc Define and, within the Id inspector, click on the drop-down button beside the Class discipline. It’ll present all of the lessons in your undertaking that may suit your chosen object. On this case, choose PlayersViewController.

Changing ViewController class

Now, when the storyboard creates an occasion of this scene, it is going to be of sophistication PlayersViewController. Subsequent, you need to configure the desk view to show information dynamically.

Dynamic Cells

First, change the the kind of the content material within the desk view from Static Cells to Dynamic Prototypes. Then, delete two of the cells within the desk view, in order that there’s only one left.

Subsequent, choose the remaining cell, open the Attributes inspector and enter PlayerCell within the Identifier discipline.

Change Cell Identifier

To inform the desk view to create your customized cell, you want to have the ability to establish it. That is what the Identifier worth is. It offers you the means to reference the cell you need from the code.

Subsequent, add this extension on the finish of PlayersViewController.swift:

extension PlayersViewController

You simply created a brand new extension for PlayersViewController with two strategies.
The primary returns the variety of cells to be displayed and the second creates and returns a cell utilizing the identifier you set beforehand.

Observe: Extensions are a good way to maintain your code organized. You may outline them in the identical Swift file or in numerous recordsdata. Make it a behavior to maintain your code organized. You may study extra about extensions from Apple’s Swift docs.

Construct and run, and also you’ll see three equivalent cells. The knowledge displayed on the cell is strictly what’s declared within the storyboard, multiplied by three. Time to make issues extra dynamic.

Simulator Screenshot

Defining a New Cell Class

The present cell has two labels and one picture, however there isn’t any approach to set these values dynamically through code. The default UITableViewCell doesn’t have entry to such elements.

Very like you probably did with the view controller, you’ll create a brand new cell class and outline a reference between its elements and the brand new class itself.

Proper-click on the Views folder and choose New File. This time, choose Cocoa Contact Class. Then, set the title of the file to PlayerCell and make it a subclass of UITableViewCell.

New Cell File

It is a quicker approach to robotically create lessons from Xcode as a substitute of making an empty file. It has the whole lot already arrange for you, and that boilerplate code will fluctuate primarily based on the subclass you specified.

For now, ignore the auto-generated strategies and add this on the prime of your class:

@IBOutlet weak var gameLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratingImageView: UIImageView!

These are the references you’ll use to entry the weather on the cell. However what’s that @IBOutlet? It’s a key phrase for the storyboard and is brief for Interface Builder Outlet. It tells the compiler that these properties will hook up with some views on the storyboard.

Open Essential.storyboard, choose the cell within the Participant Scene. Within the Id inspector, change the category to PlayerCell.

Change Cell class

Now, open the Connections inspector; you’ll see the next:

Connections Inspector

These are the three properties that you just outlined within the class. Fairly sensible, isn’t it? :]

Now, drag from the small circle beside the property title to the view on the cell that represents it.

Connecting Outlets

Do the identical for all three to attach the views on the cell.

It’s now time to indicate actual details about a participant.

Binding the Gamers

The primary possibility is to immediately set the values on the cell inside tableView(_:cellForRowAt:). The second is to go a participant occasion to the cell and let the cell extract values from it.

Generally, the primary possibility is extra handy and simpler, however steadily you’ll find yourself having loads of code in tableView(_:cellForRowAt:). For the gamers, apply the second possibility.

In PlayerCell.swift, add the next proper after the outlet declarations:

// 1:
var participant: Participant?

// 2:
non-public func picture(forRating score: Int) -> UIImage?
let imageName = “(score)Stars”
return UIImage(named: imageName)

The primary is a property of kind Participant, with a block that will get executed when its worth is ready. Such a block will set the values on the three elements related to the cell. The second is a technique to fetch the suitable picture primarily based on the score of the participant.

Now, go to PlayersViewController.swift, and proper earlier than the return of the cell in tableView(_:cellForRowAt:) add this:

cell.participant = playersDataSource.participant(at: indexPath)

Wait… What is that this error!?

Error Message

You added the participant to the cell class, so why is Xcode complaining about it?

Proper now, the return kind of cell continues to be a UITableViewCell.

Cell class

dequeueReusableCell(withIdentifier:for:) returns an occasion of a cell with the identifier you present as a kind of UITableViewCell. However because you specified the category of that cell is PlayerCell, it’s protected to solid it accordingly.

All you could do is change the road that creates the cell to the next:

let cell = tableView.dequeueReusableCell(
withIdentifier: “PlayerCell”,
for: indexPath) as! PlayerCell

Now, Xcode is pleased. Construct and run and have a good time your first working display screen! :]

Simulator Screenshot

Your app is now itemizing precise gamers. The following step is so as to add extra gamers.

Extra Gamers, Please

Create a brand new Swift File named PlayerDetailsViewController.swift within the View Controllers folder and change the import line with the next:

import UIKit

class PlayerDetailsViewController: UITableViewController
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var detailLabel: UILabel!

Then, from Essential.storyboard, set the category of the Add Participant Scene to PlayerDetailsViewController.

Earlier than attaching the shops of the brand new view controller, there’s something you need to be conscious of. You may’t connect shops in a view controller to views in dynamic cells. These cells gained’t be displayed when the view controller is initialized. However for static cells, the whole lot is ready within the storyboard, so you may safely connect views inside static cells to shops within the view controller.

Join detailLabel to the label within the second cell titled Element, and nameTextField to the textual content discipline within the first cell.

Connectiong Outlets

Now, in PlayerDetailsViewController.swift add this property earlier than the declaration of the shops.

var recreation = “”
didSet

It will save the secret. Any time this property worth is up to date, the label can even be up to date.

Lastly, add this on the finish of the category:

override func viewDidLoad()
recreation = “Chess”

The view controller will name viewDidLoad() as soon as when it hundreds all its views in reminiscence. Since updating the sport worth will replace the view, it is smart to do that when the views completed loading.

Observe: Shops may have values after the view controller hundreds the views and executes viewDidLoad(), not with the initialization.

Construct and run, faucet the + button within the higher proper nook to open the add participant display screen.

Simulator Add Player Screen

It doesn’t really feel that a lot has modified apart from the the sport is now Chess. Earlier than you add the performance so as to add gamers, repair it so the Cancel and Completed buttons do one thing.

Unwind Segues

Each Cancel and Completed have a typical habits of returning again to the itemizing display screen. Completed will do extra than simply that, however begin with that widespread motion.

In PlayersViewController.swift, add the next extension:

extension PlayersViewController

Return to Essential.storyboard. Management-drag from the Cancel button to the third icon within the bar above the scene within the storyboard. Choose cancelToPlayersViewController: from the pop-up. Do the identical for the Completed button, however choose savePlayerDetail:.

Adding Unwind Segues

Construct and run. Open the add participant display screen and take a look at the 2 buttons.

Segues in Action

It labored, however how?

The 2 strategies you added are Unwind Segues. They’re mainly exit segues to the view controller they’re applied on. Every button is utilizing its personal segue to return to the PlayersViewController.

Xcode identifies Unwind segues from their distinctive signature: A technique that takes one parameter of kind UIStoryboardSegue.

Once you faucet the + button from the itemizing display screen, it triggers a segue to current a navigation controller, which in flip triggers a segue to indicate the add participant scene. Unwind segues will robotically reverse all of the segues from the scene you’re exiting again to the scene you’re returning to.

You may have added just one technique as a substitute of two, however you continue to want so as to add the code for saving the brand new participant with the Completed motion. For now, you completed the Cancel motion. Now, it’s time to truly save newly created gamers.

Creating the New Participant

There are two steps to avoid wasting new gamers:

Seize the participant info (title, recreation and score) inside the shape, and create a full participant occasion with it.
Go the occasion to the itemizing display screen to avoid wasting and show.

Sounds easy, proper? The add participant scene already has a textual content discipline to put in writing the participant’s title, and it’s already related to an outlet, in order that’s prepared. You need to use any score worth. For now, use one star because it’s a brand new participant. The one lacking merchandise is the sport. It’s set as Chess at present, however it may well’t keep like that completely.

Creating GamePicker View Controller

Once you faucet on the second cell within the add participant scene, it opens an inventory of video games. However, when you choose one, nothing occurs. Neither is chess chosen by default.

To have the ability to do something, you could have a category for this view controller. Create a brand new Swift File named GamePickerViewController.swift. Substitute the import assertion with the next:

import UIKit

class GamePickerViewController: UITableViewController
let gamesDataSource = GamesDataSource()

Nothing particular right here, virtually equivalent to the gamers checklist. A brand new kind that subclasses UITableViewController, and comprises a property that acts as the information supply for video games.

Open Essential.storyboard, choose the Select Recreation Scene and alter its class to GamePickerViewController.

Then choose its Desk View and alter its Content material worth to Dynamic Prototypes, and the variety of Prototype Cells to 1.

Attributes Inspector

Set the Identifier of the one cell left to GameCell.

Add the next on the finish of GamePickerViewController.swift:

extension GamePickerViewController
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection part: Int
) -> Int

override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell

The primary technique returns the variety of video games the information supply has. And the second creates a cell utilizing the identifier you will have set within the storyboard, then units the textual content of textLabel to the sport’s title.

Construct and run, attain the video games checklist, and it ought to look the identical as earlier than you utilized any adjustments.

Simulator: GamePickerViewController

The Video games checklist now exhibits the identical information, however as a substitute of being set on the storyboard, they’re now loaded programmatically from gamesDataSource. Discover that you just didn’t subclass the cell this time.

The cells on this scene have their Type set to Fundamental. That type offers the cell a default textual content label accessible by way of the property textLabel.

Cell Style Selection

Choosing the Recreation

Tapping any of the video games gained’t do something besides give the cell a grey background. Undoubtedly, that’s not the specified habits. What it ought to do is:

Choose the brand new recreation.
Return again to the shape.
Present the shape the chosen recreation

You’ll do the second step first since its simpler. Open PlayerDetailsViewController.swift and add the next code on the finish of the file:

extension PlayerDetailsViewController

It is a easy Unwind segue to return again to the Add Participant Scene.

Return to Essential.storyboard and Management-drag from the GameCell to the Exit icon above the scene. Choose unwindWithSelectedGameWithSegue: below Choice Segue.

Connectiong Segue

Construct and run. Attain the video games checklist and choose any of the video games.

Game Selection Running

The video games checklist will robotically exit as soon as you choose any merchandise, and can return to the earlier scene. Wouldn’t it’s cool if the checklist can present what has already been chosen?

Passing Parameters With Segues

Chess is already set because the default recreation, so why is it not exhibiting a checkmark beside it when the video games checklist seems? To implement this, the Add Participant Scene must go the sport title to Select Recreation Scene every time it opens. However the storyboard is already dealing with opening the scene itself, and there’s no code for this in any respect. However there’s a hook.

When a segue is triggered, the view controller that triggered it’s going to name the tactic put together(for:sender:) and can present the segue that it’s dealing with. There are two vital properties within the segue you’ll steadily use: identifier and vacation spot. The identifier is only a string, identical to the cell identifier you already used. It’s additionally empty by default. The vacation spot is the view controller occasion that the segue will go to.

As soon as you understand which segue is going on from its identifier, you may solid the vacation spot object to the view controller class you understand. Let’s strive that.

Open Essential.storyboard and choose the segue named Present segue to “Select Recreation”. Then from the Attributes inspector change its Identifier to PickGame.

Setting Segue Identifier

Then, in PlayerDetailsViewController.swift, add the next inside the category after viewDidLoad():

override func put together(for segue: UIStoryboardSegue, sender: Any?)
if segue.identifier == “PickGame”,
let gamePickerViewController = segue.vacation spot as? GamePickerViewController

If the segue’s identifier is PickGame, solid the vacation spot view controller as GamePickerViewController so you may entry its properties. Set the present worth of recreation as the chosen recreation.

Lastly, in GamePickerViewController.swift, add the next in tableView(_:cellForRowAt:) proper earlier than the return:

if indexPath.row == gamesDataSource.selectedGameIndex else
cell.accessoryType = .none

Construct and run. Open the video games checklist display screen and also you’ll see that Chess is already marked.

Simulator Screenshot

To finalize the sport choice, in GamePickerViewController.swift, add the next on the finish of the file:

extension GamePickerViewController
override func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
)
// 1
tableView.deselectRow(at: indexPath, animated: true)
// 2
if let index = gamesDataSource.selectedGameIndex
let cell = tableView.cellForRow(at: IndexPath(row: index, part: zero))
cell?.accessoryType = .none

// three
gamesDataSource.selectGame(at: indexPath)
// four
let cell = tableView.cellForRow(at: indexPath)
cell?.accessoryType = .checkmark

Each time a cell in a desk view is chosen, tableView(_:didSelectRowAt:) will execute the next steps:

Take away the grey choice background that seems by default.
Get the beforehand chosen recreation and take away the checkmark from its cell.
Choose the brand new recreation within the information supply.
Mark the brand new cell with the checkmark.

Open PlayerDetailsViewController.swift and add the next inside unwindWithSelectedGame(segue:):

if let gamePickerViewController = segue.supply as? GamePickerViewController,
let selectedGame = gamePickerViewController.gamesDataSource.selectedGame
recreation = selectedGame

If the supply view controller of the segue is of kind GamePickerViewController and there’s a legitimate chosen recreation within the information supply, then set the sport to the brand new one.

Construct and run, and select a recreation apart from chess. The worth Chess just isn’t up to date! Why is that?

Simulator: Choosing a Game

Synchronizing Segues With Actions

When you choose a cell, the unwind segue is triggered first, and the PlayerDetailsViewController is studying the chosen recreation from the information supply earlier than tableView(_:didSelectRowAt:) in GamePickerViewController is executed. That’s the rationale nothing has modified.

Routinely triggered segues usually are not meant to work hand-in-hand with actions when the order of execution is vital. To repair this, you could inform the view controller when to set off the segue.

UIViewController has performSegue(withIdentifier:sender:). Its job is to help you set off a segue if you need it triggered.

To repair the difficulty, first take away the segue that the cell triggers on choice. Choose the Exit icon in Select Recreation Scene, and from the Connections inspector take away the motion related to the Choice outlet by clicking on the small x.

The segue wants to attach from the view controller itself so nothing else triggers it. To create a segue from the controller Management-drag from the View Controller icon to the Exit icon. Give this new segue the identifier unwind to reference it from the code.

Renaming Segue

Open GamePickerViewController.swift and, on the finish of tableView(_:didSelectRowAt:), add the next:

performSegue(withIdentifier: “unwind”, sender: cell)

Construct and run and attempt to change the sport. It really works this time. :]

Selecting a Game

Time to renew the duty of saving a brand new participant.

Saving the New Participant

The final step is to truly save the brand new Participant object when the person faucets Completed. These are the actions wanted to complete this step:

Solely when the segue related to the Completed button is triggered, assemble a brand new Participant object and retailer it within the controller.
When the unwind segue of the Completed button is carried out, append that saved object to the information supply.

Open Essential.storyboard and, below Add Participant Scene, choose the unwind segue triggered by Completed. Its title is Unwind segue to savePlayerDetail: within the Doc Define. Give it the identifier SavePlayerDetail.

Open PlayerDetailsViewController.swift. Add this property on the prime of the category:

var participant: Participant?

Then, add the next in the beginning of put together(for:sender:) in the identical file:

if segue.identifier == “SavePlayerDetail”,
let playerName = nameTextField.textual content,
let gameName = detailLabel.textual content
participant = Participant(title: playerName, recreation: gameName, score: 1)

This creates a brand new Participant if the shape is full.

In PlayersViewController.swift, add the next because the implementation of savePlayerDetail(_:)

guard
let playerDetailsViewController = segue.supply as? PlayerDetailsViewController,
let participant = playerDetailsViewController.participant
else
return

playersDataSource.append(participant: participant, to: tableView)

Construct and run, then add a brand new participant in your app. It really works like a attraction! :]

Adding a Player

First Responders

A pleasant enchancment is to have the textual content discipline for the participant’s title robotically chosen and simply able to kind, as a substitute of tapping the sphere every time you need to add a participant.

In PlayerDetailsViewController.swift, add this line in viewDidLoad()

nameTextField.becomeFirstResponder()

It will give the textual content discipline focus simply as in case you tapped on it your self.

Construct and run and begin including a participant. The display screen will begin with the keyboard open.

Observe: Press Command-Okay to toggle the software program keyboard on & off within the simulator.

Active Textfield

Efficiency With Storyboards

Storyboards don’t have any influence in your app’s efficiency. Though you designed all of the view controllers in a single file, it doesn’t imply that they’ll all load in reminiscence collectively. Solely the view controller you’re exhibiting can be loaded, and it is going to be launched if you dismiss it.

In PlayerDetailsViewController.swift, add the next after the properties:

required init?(coder aDecoder: NSCoder)

deinit
print(“deinit PlayerDetailsViewController”)

That is to trace when a PlayerDetailsViewController occasion initializes and deinitializes by printing some textual content within the log.

Construct and run once more. Open and shut the add participant scene. You’ll see the primary log message if you open the display screen and the second if you shut it.

Storyboard Overview

Storyboard References

In greater tasks, the storyboard file can get crowded with many scenes. When working in a workforce, you’ll shortly study that storyboard recordsdata can generate conflicts when a couple of individual is engaged on them.

However worry not, there’s a treatment for that: Storyboard references. These help you break a storyboard into a number of recordsdata with out dropping any of the options illustrated to this point.

For example, you’re going to separate the circulate of itemizing and including the participant.

Open Essential.storyboard and zoom out so you may see all of the scenes. Then drag a variety rectangle to pick all of the player-related scenes. Ensure you don’t choose any extra scenes.

Scene Selection

Then, from the Xcode’s menu bar, select Editor ▸ Refactor to Storyboard. Title the brand new file Participant.storyboard. Xcode will create a brand new .storyboard file and can put the scenes you chose into it. In Essential.storyboard, you’ll discover a new merchandise created.

Storyboard Reference

This merchandise is referring to a different set of scenes in one other storyboard file. You too can insert a Storyboard Reference from the Object library in case you choose to hyperlink scenes your self. For those who construct and run, you’ll that your app capabilities precisely because it did earlier than.

The place to Go From Right here?

On this tutorial, you solely scratched the floor of what desk views can do. To study extra about them you may watch the Starting Desk Views course.
The usage of animations may also add loads of worth to your purposes with a small quantity of effort. It’s value testing the Starting iOS Animations course. Animations work properly with storyboards :]
Each programs are a part of the iOS & Swift Newbie Path if you need to study extra subjects.

When you’ve got any questions or feedback, please don’t hesitate to hitch the discussion board dialogue under.

asubhan
wordpress autoblog
amazon autoblog
affiliate autoblog
wordpress web site
web site improvement

Related posts

Platform-Conscious Widgets in Flutter [FREE]

admin

Google Play companies discontinuing updates for API ranges 14 and 15

admin

Android Studio three.5 Beta

admin

Leave a Comment