Monday, October 14, 2019

iOS Pass Data between View Controllers

iOS Passing Data between View Controllers

In iOS while working to create apps we will use multiple view controllers and sometimes we will get requirement like pass or send data from one view controller to another view controller or move from one controller to another view controller along with images and text. By using prepareforsegue method in iOS we can easily send data from one controller to another controller based on our requirement.

Generally, we will come across this kind of situation when we have a product app with hundreds of products in table view and when we click on tableview cell it should send respective product details to another controller to show the details of product.

Now we will see how to create simple iOS app to send data from one view controller to another view controller in swift with example.

Create iOS Pass Data App in Swift

To create new project in iOS open Xcode from /Applications folder directory. Once we open Xcode the welcome window will open like as shown below. In welcome window click on the second option “Create a new Xcode Project” or choose File à New à Project.
  
Xcode application to create ios project

After selecting “Create a new Xcode project” a new window will open in that we need to choose template.

The new Xcode window will contain several built-in app templates to implement common type of iOS apps like page based apps, tab-based apps, games, table-view apps, etc. These templates are having pre-configured interface and source code files. 

For this iOS Table View example, we will use most basic template “Single View Application”. To select this one, Go to the iOS section in left side à select Application à In main area of dialog select “Single View Application” and then click on next button like as shown below.

Select single view application from ios xcode templates

After click Next we will get window like as shown below, in this we need to mention project name and other details for our application.

Product Name: “Pass Data from ViewController”

The name whatever we enter in Product Name section will be used for the project and app.

Organization Name: “Tutlane”

You can enter the name of your organization or your own name or you can leave it as blank.

Organization Identifier: “com.developersociety”

Enter your organization identifier in case if you don't have any organization identifier enter com.example.

Bundle Identifier: This value will generate automatically based on the values we entered in Product Name and Organization Identifier.

Language: “Swift”

Select language type as “Swift” because we are going to develop applications using swift.

Devices: “Universal”

Choose Devices options as Universal it means that one application is for all apple devices in case if you have any specific requirement to run app only for iPad then you can choose the iPad option to make your application restricted to run only on iPad devices.

Use Core Data: Unselected

This option is used for database operations. In case if you have any database related operations in your application select this option otherwise unselect the option.

Include Unit Tests: Unselected

In case if you need unit tests for your application then select this option otherwise unselect it.

Include UI Tests: Unselected

In case if you need UI tests for your application then select this option otherwise unselect it.

Once you finished entering all the options then click on Next button like as shown below.

create new ios pass data between controllers project in xcode

Once we click on Next button new dialog will open in that we need to select the location to save our project. Once you select the location to save project then click on Create button like as shown below.

Give path to save new ios application in xcode

After click on Create button the Xcode will create and open a new project. In our project Main.storyboard and ViewController.swift are the main files which we used to design the app user interface and to maintain source code. 

Main.storyboard - Its visual interface editor and we will use this file to design our app user interface 

ViewController.swift - It contains source code of our application and we use this file to write any code related to our app.

Now in project select Main.storyboard file the Xcode will open visual interface editor like as shown below.

ios pass data between view controller project storyboard file in xcode

Now select ViewController.swift file in your project that view will be like as shown below.

ios pass data between view controller project viewcontroller.swift file in xcode

Add iOS UI Controls to View in Xcode

Now we will add controls to our application for that open Object Library. The Object Library will appear at the bottom of Xcode in right side. In case if you don't find Object library, click on the button which is at the third position from the left in the library selector bar like as shown below. (Alternatively you can choose View à Utilities à Show Object Library.)

Object Library in Xcode Application to Search for UI Controls

As we discussed our user interface will be in Main.storyboard file so open Main.storyboard file. Now in Object library search for the table view in Filter field then drag and drop the table view into Main.storyboard ViewController like as shown below.

ios tableview add ui controls to storyboard in xcode

Now click on table view and you see that in Prototype cells the textbox is zero give it here “1” and style should be “Grouped” like as shown below.

ios tableview change prototype cells in xcode

Now we will make connection between Table View and View Controller for that click on yellow button and drag the cursor from yellow button and drop it on data source and you should do the same process for connecting delegate also like as shown below.

ios map tableview to datasource and delegate in xcode

Now we will add images to our assets folder for that select the images drag and drop into the left side assets folder in our application like as shown below.

ios tableview with custom cell add images to assets folder in xcode

For the implementation of Table View move to the ViewController.Swift file first add the two classes which is UITABLEVIEWDATASOURCE and UITABLEVIEWDELEGATE make an array with name devCourses using let keyword which will show in table view. let keyword is basically the constant keyword its mean that the value can’t be change after declaration and the second array devCousesImages is for images and it contains the name of image which is in assets folder.

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
let devCourses = [("Laravel"),("Swift"),("Apple"),("Window"),("Android")]
let devCousesImages = [UIImage(named: "Laravel"), UIImage(named: "swift"), UIImage(named: "Laravel"), UIImage(named: "window"), UIImage(named: "Android")]
Now move to Main.storyboard file and drag the label and image view and drop into the table View cell like as shown below.

ios tableview custom cell with image view and label controls

 Now we will add new file in our ios tableview applications for that go to the File à click on New à click on file button like as shown below.

ios tableview custom cell add new file in application

Once we click File new templates section will open in that choose the “Cocoa Touch Class” and then click on next button like as shown below

Add new class cocoa touch class in ios tableview controller

Give the class name and extend with subclass “UITableViewCell” and set the language swift the purpose of creating this class is to make our own cell to show the image on top that we drag and drop the label and image view. 

Give name to new class file in ios tableview custom cell with images

Now click on cell and assign the class which we created and remember that the name of class should be same otherwise our label and image view will not connect with the class.

ios tableview custom cell with image map custom class to tableview

Connect iOS UI Controls to Code in Swift

Now we will make connection between controls and ViewController.Swift code for that click on assistant button (overlap circle) in Xcode toolbar right side corner like as shown below.

Assistant Editor in iOS Xcode to Mapp Controls with Code

To map the controls, press Ctrl button in keyboard and drag the Image View from canvas interface and drop into TableTableViewCell file same way map label control also like as shown below.

ios uitableview custom cell with images map controls to viewcontroller.swift file

Now click on cell and give its identifier name as cell. Here you are not restricted to give name as “cell” if you want give your own name also based on your requirements.

ios tableview with custom cell images change identifier name in xcode

Now our task is to show the data in table view for that we have three methods which are mandatory to implement in Table View those are given below. 

The first method is “numberOfSectionsInTableView” by using this method we can return number of sections which required in our applications. Present we need only one section so we are returning only 1.

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
Now second method is “tableView” here we need to define number of row sections which we need show in table view. 

In case If we want to show only five rows in table view then we need to mention it as “return 5” otherwise if we want to show all the rows present in array then we need to mention array name with count method like as mentioned below.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return devCourses.count
}
Now the third method is “tableView” with “cellForRowAtIndexPath” basically this is the method where we assign array data to label in our Table View cells. Our method need to be like as shown below.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell=tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) asTableTableViewCell
let courseTitle = devCourses[indexPath .row]
let Images = devCousesImages[indexPath .row]
cell.label.text=courseTitle
cell.photo.image=Images
return cell
}
Now go to Main.storyboard file and search the ViewController in object library drag the ViewController and drop into the Main.storyboard file now we have two ViewControllers default one and new one which we added.

ios add view controller to storyboard file in xcode

Now click on first ViewController which is having table view and go to the Editor à then click on Embed In à then add the Navigation Controller now you have three ViewControllers.

ios add navigation controller to swift application in xcode

Now go to the File option à then click on New à then click on File option like as shown below.

ios tableview custom cell add new file in application

Now choose the “Cocoa Touch Class” and click on Next button like as shown below

Add new class cocoa touch class in ios tableview controller

Give class name and extend with subclass “UIViewController” and set the Language type swift like as shown below. The purpose of creating this class is to pass the data from tableview cell to another ViewController.

Give name to new class file in ios pass data between view controllers in xcode

Now go the Main.storyboard section and click on Third View Controller and assign the class which is created now called “ThirdViewController”.

ios map new class file to view controller in xcode

Now we will map our table viewcontroller with third viewcontroller for that press Ctrl button in keyboard and click on yellow circle sign in table ViewController and drop into the third ViewController like as shown below.

ios map viewcontroller to another view controller in xcode

Now click on the connection which is appear between the table View Controller and third view controller and set the name of segue identifier, here we set the name of identifier as “SendDataSegue”.

ios change segue connection name in pass data between view controller app in xcode

Now go Third ViewController and search for the label in Object Library then drag and drop into Third ViewController same way add Image view control also in Third ViewController.

ios add ui controls to pass data between view controllers in swift app

Now we will make connection between label and imageview controls to ThirdViewController.Swift file code for that click on assistant button (overlap circle) in Xcode toolbar right side corner like as shown below. To map the controls, press Ctrl button in keyboard and drag the Image View from canvas interface and drop into ThirdViewController file same way map label control also like as shown below

ios map ui controls to viewcontroller code in swift

Once we done all the settings we need to write custom code to show image and image details in Third ViewController. Our ThirdViewController.swift file should contain code like as shown below

class ThirdViewController: UIViewController {
@IBOutlet weak var SegueLabel: UILabel!
var textt = String()
@IBOutlet weak var photo: UIImageView!
var image = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
self.photo.image=self.image
self.SegueLabel.text = self.textt
}
}
Our main ViewController.swift file will contain code like as shown below

//  ViewController.swift
//  TableView
//  Created by Tutlane on 15/05/2016.
//  Copyright © 2016 Tutlane. All rights reserved.

import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let devCourses = [("Laravel"),("Swift"),("Apple"),("Window"),("Android")]
let devCousesImages = [UIImage(named: "Laravel"), UIImage(named: "swift"), UIImage(named: "Laravel"), UIImage(named: "window"), UIImage(named: "Android")]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
returndevCourses.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell=tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) asTableTableViewCell
cell.photo.image=self.devCousesImages[indexPath .row]
cell.label.text=self.devCourses[indexPath .row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.performSegueWithIdentifier("SendDataSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SendDataSegue" {
let indexPaths=self.tableView!.indexPathsForSelectedRows!
let indexPath = indexPaths[0as NSIndexPath
let vc = segue.destinationViewController asThirdViewController
vc.image = self.devCousesImages[indexPath.row]!
vc.textt = self.devCourses[indexPath.row]
}
}
}
Now we will run and check the output of application. To run application, select the required simulator (Here we selected iPhone 6s Plus) and click on Play button, located at the top-left corner of the Xcode toolbar like as shown below.

Run ios tableview example in xcode using swimulator

Output of iOS Pass Data b/w Controllers App

Following is the result of iOS pass data between controller application. If you observe we are showing table view data with images as a single-column list with multiple row sections once we click on table view cell that information passed to another viewcontroller like as shown below

ios passing data between view controllers app example result or output

This is how we can pass data between view controllers in iOS swift applications based on our requirements.

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...