Saturday, April 1, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

Use Storyboards to Build Navigation Controller and UITableView

learningcode_x1mckf by learningcode_x1mckf
December 13, 2022
in Swift
0
Use Storyboards to Build Navigation Controller and UITableView
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


You might also like

Swift Against Humanity – Hacking with Swift

Introducing MotionBar – the Animated Tab Bar Library

Introducing – AI Utils for macOS

By now, should you’ve adopted our tutorials, it’s best to have a fundamental understanding about UITableView and easy methods to construct a easy app. This week, we’ll speak about one thing new – Storyboards. This is likely one of the most fun options launched in Xcode 4.2 and iOS 5 SDK. It makes your life, as an iOS developer, easier and allows you to simply design the person interface of your iOS app.

On this tutorial, we’ll present you easy methods to use Storyboards to construct a Navigation interface and combine it with UITableView. We attempt to maintain factor easy and concentrate on explaining the idea. So no fancy interface or fairly graphic. We’ll go away the art work to future tutorials.

Okay, let’s get began.

What’s Navigation Controller?

Earlier than we transfer onto the coding half, as regular, let’s have a quick introduction about Navigation Controller and Storyboards.

Like desk view, navigation controller is one other UI aspect you generally discover in iOS app. It offers a drill-down interface for hierarchical content material. Check out the built-in Pictures app, YouTube, and Contacts. They’re all constructed utilizing Navigation Controller to show hierarchical content material. Normally desk view and navigation controller work hand in hand for many of the apps. This doesn’t imply it’s a must to use each collectively, nevertheless.

Photos App Navigation Controller

An instance of Navigation Controller – Pictures App

Storyboards Overview

Storyboard, as talked about earlier, is a brand new function obtainable because the launch of Xcode 4.2. It presents an entire new approach for iOS developer to create and design person interface. Earlier than the introduction of Storyboard, it’s particularly laborious for newbie to create navigation (and tab) interface. Each interface is saved in a separate nib file. On prime of it, it’s a must to write code to hyperlink all interfaces collectively and describe how the navigation works.

With Storyboards, all screens are saved in a single file. This provides you a conceptual overview of the visible illustration for the app and exhibits you the way the screens are related. Xcode offers a built-in editor to format the Storyboards. You possibly can outline the transition (generally known as segues) between numerous screens merely utilizing level and click on. This doesn’t imply you do not want to write down code for the person interface. However Storyboards considerably cut back the quantity of code you might want to write. Here’s a pattern screenshot to indicate you the way Storyboards appear like in Xcode.

Storyboards Explained

Storyboards – Scene and Segue

Scene and Segues

When working with Storyboards, Scene and Segues are two phrases you all the time come throughout. Inside a Storyboard, a scene refers to a single view controller and its view. Every scene has a dock, which is used primarily to make motion and outlet connections between the view controller and its views.

Segue sits between two scenes and manages the transition between two scenes. Push and Modal are two widespread forms of transition.

Creating Navigation Controller in Storyboards

Now let’s get our palms soiled and create our personal Storyboards. On this tutorial, we’ll construct a easy app that makes use of each UITableView and UINavigationController. We use the desk view to show an inventory of recipes. When customers choose any of the recipe, the app navigates to the subsequent display displaying the small print. It’ll be straightforward.

First, hearth up Xcode (ensure you’re utilizing 4.2 or up) and create a brand new venture utilizing “Single View utility” template.

Choose Xcode Template

Xcode Challenge Template Choice

Click on “Subsequent” to proceed. In reference to the under determine, fill in all of the required values for the Xcode venture. Be sure you allows the “Use Storyboards” choice.

RecipeBook Xcode Project

RecipeBook Xcode Challenge

Click on “Subsequent” to proceed. Xcode then asks you the place you saves the “SimpleTable” venture. Decide any folder (e.g. Desktop) to avoid wasting your venture.

You could discover there’s a minor distinction within the Xcode venture, as in contrast with these you got here throughout in earlier tutorials. The .xib file (interface builder) is changed with the MainStoryboard.storyboard file.

Default Storyboard in Xcode

Default Storyboard in Xcode

By default, Xcode creates an ordinary view controller. As we’ll use navigation controller to manage the display navigation, we first change the view controller to navigation controller. Choose the Merely choose “Editor” within the menu and choose “Embed in”, adopted by “Navigation Controller”.

Storyboard Embed in Navigation Controller

Embed View Controller in Navigation Controller

Xcode robotically embeds the RecipeBook View Controller with Navigation Controller. Your display ought to appear like this:

Storyboard Added with Navigation Controller

Embedded View Controller with Navigation Controller

Earlier than transferring on, let’s run the app and see the way it seems. Hit the “Run” button and it’s best to get an app with a clean view however added with a navigation bar. This exhibits you’ve efficiently embed your RecipeBook View Controller in a Navigation Controller.

RecipeBookApp Empty

Recipe Ebook App with Empty View Controller

Including Desk View for Your Knowledge

Subsequent, we’ll add a desk view for displaying our recipes. Choose “Desk View” in Object Library and drag it into “Recipe Ebook View Controller”.

Please word you may’t drag stuff when the editor is zoomed out. In the event you can’t drag the desk view into the view controller, zoom in and check out once more.

Storyboard Add Table View

Add Desk View to Recipe Ebook View Controller

The following factor we’ve got to do is to write down code to populate the desk knowledge (i.e. recipes). In Challenge Navigator, choose “RecipeBookViewController.h”. Append “” after “UIViewController”. Your code ought to appear like under:

#import <UIKit/UIKit.h>

 

@interface RecipeBookViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

 

@finish

In the event you’ve learn our Easy Desk tutorial, you have to be very aware of the code. I’ll not clarify the code in particulars. In the event you discover it tough to observe, take a look at our earlier tutorial.

Subsequent, choose “RecipeBookViewController.m” and outline an occasion variable (i.e. recipes array) for holding the desk knowledge.

@implementation RecipeBookViewController

    NSArray *recipes;

Within the “viewDidLoad” technique, add the next code to initialize the “recipes” array:

– (void)viewDidLoad

    [super viewDidLoad];

// Initialize desk knowledge

    recipes = [NSArray arrayWithObjects:@”Egg Benedict”, @”Mushroom Risotto”, @”Full Breakfast”, @”Hamburger”, @”Ham and Egg Sandwich”, @”Creme Brelee”, @”White Chocolate Donut”, @”Starbucks Coffee”, @”Vegetable Curry”, @”Instant Noodle with Egg”, @”Noodle with BBQ Pork”, @”Japanese Noodle with Pork”, @”Green Tea”, @”Thai Shrimp Cake”, @”Angry Birds Cake”, @”Ham and Cheese Panini”, nil];

Lastly, we’ve got to implement two datasource strategies to populate the desk knowledge: “tableView:numberOfRowsInSection” and “tableView:cellForRowAtIndexPath”. Recalled that these two strategies are a part of the UITableViewDataSource protocol, it’s obligatory to implement the strategies when configuring a UITableView. The primary technique is used to tell the desk view what number of rows are within the part, whereas the second technique is used to fill the cell knowledge. So let’s add the under code.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)part

    return [recipes count];

 

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    static NSString *simpleTableIdentifier = @”RecipeCell”;

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    

    if (cell == nil)

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

    

    

    cell.textLabel.textual content = [recipes objectAtIndex:indexPath.row];

    return cell;

On your reference, that is the whole supply code of “RecipeBookViewController.m”.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

//

//  RecipeBookViewController.m

//  RecipeBook

//

//  Created by Simon Ng on 14/6/12.

//  Copyright (c) 2012 Appcoda. All rights reserved.

//

 

#import “RecipeBookViewController.h”

 

@interface RecipeBookViewController ()

 

@finish

 

@implementation RecipeBookViewController

    NSArray *recipes;

 

– (void)viewDidLoad

    [super viewDidLoad];

// Initialize desk knowledge

    recipes = [NSArray arrayWithObjects:@”Egg Benedict”, @”Mushroom Risotto”, @”Full Breakfast”, @”Hamburger”, @”Ham and Egg Sandwich”, @”Creme Brelee”, @”White Chocolate Donut”, @”Starbucks Coffee”, @”Vegetable Curry”, @”Instant Noodle with Egg”, @”Noodle with BBQ Pork”, @”Japanese Noodle with Pork”, @”Green Tea”, @”Thai Shrimp Cake”, @”Angry Birds Cake”, @”Ham and Cheese Panini”, nil];

 

 

– (void)viewDidUnload

    [super viewDidUnload];

    // Launch any retained subviews of the primary view.

 

– (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);

 

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)part

    return [recipes count];

 

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    static NSString *simpleTableIdentifier = @”RecipeCell”;

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    

    if (cell == nil)

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

    

    

    cell.textLabel.textual content = [recipes objectAtIndex:indexPath.row];

    return cell;

 

@finish

Lastly, we’ve got to determine the connection between the Desk View and the 2 strategies we simply created. Return to the Storyboard. Press and maintain the Management key in your keyboard, choose the “Desk View” and drag to the View Controller icon. Your display ought to appear like this:

Storyboard TableView Datasource

Join Desk View with Datasource and Delegate

Launch each buttons and a pop-up exhibits each “dataSource” & “delegate”. Choose “dataSource” to make a connection between the Desk View and its knowledge supply. Repeat the above steps and make a reference to the delegate.

Storyboard TableView Connect Datasource

Datasource and Delegate Shops

Earlier than we take a look at out the app, one very last thing to do is add a title for the navigation bar. Merely choose the navigation bar of “Recipe Ebook View Controller” and fill within the “Title” beneath “Attributes Inspector”. Bear in mind to hit ENTER after keying within the title to effectuate the change.

Storyboard Add Navigation Bar Title

Assign a Title for the Navigation Bar

Now, it’s time to execute your code. Hit the Run button and take a look at out your app. In case your code is appropriate, it’s best to find yourself with an app displaying an inventory of recipes. The app must be similar to the Simple Table app you’ve constructed earlier than. Right here, the most important distinction is it’s embedded in a Navigation Controller.

Storyboard Navigation Bar Title

Easy Desk App with Navigation Bar

Introducing Prototype Cell

Do you keep in mind how we customize the table cell? A number of weeks in the past, we confirmed you easy methods to design your individual customized desk cell utilizing Interface Builder. In short, you might want to create a separate nib for the cell and programmatically load it within the desk. With the introduction of Prototype Cell in Storyboard, it’s a lot easier to create a customized cell. Prototype cell lets you simply design the format of a desk cell proper within the Storyboard editor.

We won’t go into the small print of the customization on this tutorial however simply merely add “Disclosure Indicator” within the cell.

So as to add a prototype cell, choose the Desk View. Below “Attributes Inspector”, change the “Prototype Cells” worth from “0” to “1”. As quickly as you modify the worth, Xcode robotically exhibits you a prototype cell. So as to present you one other desk fashion, let’s additionally change the “Type” choice from “Plain” to “Group”.

Storyboard Prototype Cell

Including Prototype Cell for Desk View

Subsequent, choose the “Prototype Cell”. You need to be capable of customise the choices of the cell. To show a disclosure indication for every cell, change the “Accent” to “Disclosure Indicator”. It’s vital to outline the Reuse identifier. You possibly can consider this identifier because the cell’s ID. We will use it to confer with a specific prototype cell. Right here, we outline the identifier as “RecipeCell” that matches with our code.

Storyboard Edit Prototype Cell

Outline Identifier and Accent for Prototype Cell

Now, run the app once more. It seems a bit distinction and we’re making progress. We’ve modified the desk fashion to “Grouped” fashion and added the disclosure indicator.

Storyboard Recipe App with Disclosure

Recipe App with Disclosure Indicator

Including Element View Controller

Lastly it involves the final a part of the tutorial. What’s lacking is the element view controller that exhibits the small print of recipe. The element view controller must be displayed when person faucets on any of the recipes.

Okay, let’s add a brand new View Controller because the element view controller.

Storyboard Create Detail View Controller

Add a New View Controller

The first function of this tutorial is to indicate you easy methods to implement navigation controller. We’ll maintain the element view so simple as attainable. Let’s only a label displaying the recipe identify. Drag the label from Object library and place it on the middle of the view. You could change the font measurement or sort to make the label look higher.

Subsequent, we’ll add a segue to attach the prototype cell and the brand new View Controller. It’s very easy so as to add a segue object. Press and maintain the management key, click on on the prototype cell and drag to the View Controller.

Storyboard Add Segue

Join Each Scenes with Segue

Launch each buttons and a pop-up exhibits three forms of Segues (push, modal and customized).

Storyboard Segues

Storyboard Segues (Push, Modal and Customized)

As defined earlier than, segue defines the kind of transition between scenes. For normal navigation, we use “Push”. As soon as chosen, Xcode robotically connects each scenes with Push segue. Your display ought to appear like this:

Storyboard Segue Connection

Storyboard Segue

Now, let’s run the app once more. As you choose any of the recipes, the app exhibits the element view controller. Although the element view controller simply exhibits a label, you already make the navigation work.

Receipe App With Detail Controller

Receipe App With Element Controller

What’s Coming Subsequent?

This can be a prolonged tutorial and eventually it involves an finish. I hope you’ve got a greater understanding about Storyboards and know easy methods to design your individual navigation controller. Nonetheless, there may be nonetheless one factor left: how will you cross the recipe identify from the “Recipe Ebook View Controller” to the “Element View Controller”? I’ll go away this to the subsequent tutorial which must be printed by the tip of this week.

Storyboards, UITableView and Navigation Controller are the basic UI parts and generally used when constructing iOS apps. So take a while to undergo the tutorial and ensure you have an intensive understanding of the fabric. As all the time, you probably have any questions, go away me remark or ask it at our forum.

Replace #1: The next tutorial about data passing is now obtainable!

Replace #2: Now you can download the full source code in your reference.





Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Swift Against Humanity – Hacking with Swift

by learningcode_x1mckf
April 1, 2023
0
Swift Against Humanity – Hacking with Swift

So that you suppose you already know Swift? Assume once more! Recent from the success of our audiobook launch, Laboratoires TwoStraws is again with an all-new card sport...

Read more

Introducing MotionBar – the Animated Tab Bar Library

by learningcode_x1mckf
March 31, 2023
0
Introducing MotionBar – the Animated Tab Bar Library

In an earlier tutorial, we shared find out how to create a customized tab bar view utilizing SwiftUI to exchange the usual tab bar. If you happen to’ve...

Read more

Introducing – AI Utils for macOS

by learningcode_x1mckf
March 24, 2023
0
Introducing – AI Utils for macOS

⚠️ REQUIRES a FREE OpenAI API key. You will get one utilizing this hyperlink. ⚠️ Improve your productiveness with our AI powered utility application. - accessible...

Read more

Encoding and decoding data using the Hummingbird framework

by learningcode_x1mckf
March 22, 2023
0
Encoding and decoding data using the Hummingbird framework

HTTP is all about sending and receiving information over the community. Initially it was solely utilized to switch HTML paperwork, however these days we use HTTP to switch...

Read more

Hummingbird routing and requests – The.Swift.Dev.

by learningcode_x1mckf
March 17, 2023
0
Hummingbird routing and requests – The.Swift.Dev.

Routing on the server facet means the server goes to ship a response primarily based on the URL path that the consumer referred to as when firing up...

Read more
Next Post
6 Best JavaScript Programming Books Ranked by Reviews

6 Best JavaScript Programming Books Ranked by Reviews

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Microsoft Launches New Resource for Java Developers — Visual Studio Magazine

Microsoft Launches New Resource for Java Developers — Visual Studio Magazine

September 30, 2022
Oracle aligns GraalVM development with Java development

Oracle aligns GraalVM development with Java development

January 7, 2023
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Central Java, Norway explore energy transition cooperation – ANTARA English

February 16, 2023

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • So why did they decide to call it Java? – InfoWorld
  • Senior Java Developer – IT-Online
  • 4 Packages for Working With Date and Time in JavaScript – MUO – MakeUseOf

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?