SlideShare a Scribd company logo
1 of 33
Swift Tableview
www.letsnurture.com
www.letsnurture.com
Create a new project
Open Xcode 6, create a new “Single Page Application” and select Swift as the
programming language.
Add a table view property
• Open the ViewController.swift class and add a
new tableview instance variable below the class
declaration.
• Add the @IBOutletInterface Builder declaration
attribute to expose the tableView property.
• “Interface Builder attributes are declaration attributes
used by Interface Builder to synchronize with Xcode.
Swift provides the following Interface Builder
attributes: IBAction, IBDesignable, IBInspectable, and
IBOutlet. These attributes are conceptually the same as
their Objective-C counterparts.”
www.letsnurture.com
www.letsnurture.com
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView
...
}
www.letsnurture.com
Conform to the UITableViewDelegate and
UITableViewDataSource protocols
To conform to the UITableViewDelegate and UITableViewDataSource protocol,
just add them separated by commas afterUIViewController in the
class declaration. (more about protocols in Apple’s Docs)
class ViewController: UIViewController,
UITableViewDataSource, UITableViewDelegate { ... }
www.letsnurture.com
Add a table view in your view controller interface
Open Main.storyboard and drag a UITableView from the library (in the lower right
corner) into the ViewController view.
www.letsnurture.com
Connect the Interface Builder outlets
Connect the dataSource, delegate and tableView outlets in interface builder. Just
right click on the table view and then connect them
www.letsnurture.com
Create the custom cell class
Create a new class above your ViewController code. Your custom cell class
should inherit from UITableViewCell! Add outlets for
the backgroundImage and titleLabel.
class CustomTableViewCell : UITableViewCell {
@IBOutlet var backgroundImage:UIImageView
@IBOutlet var titleLabel: UILabel }
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate { ... }
www.letsnurture.com
Create the custom cell interface
Right click on your applications directory and select new file.
www.letsnurture.com
Select User Interface and then the Empty template.
Select iPhone and name it CustomTableViewCell.
Open CustomTableViewCell.xib and add a UITableViewCell in it from the
component library. Select the Table View Cell and change it’s
class to CustomTableViewCell
www.letsnurture.com
After that the table view cell should change its name to Custom Table View Cell,
the backgroundImage and titleLabel outlets should be visible now.
Add an image view and a label in the cell.
Resize the cell to 320 x 320 using the size inspector. And set the row height to 320
www.letsnurture.com
Connect the cell outlets to the CustomTableCellViewCell.
Notice that custom view bind outlets to the view object and custom view
controllers bind them to the File's Owner
Add the loadItem method
• In a real life application you usualy have
more than one type of cell in a table view (or
collection view).
• By keeping the initialization logic in the cell
we can avoid code duplication or spaghetti
code.
• This cell displays an image stored on the
device and has a string title.
• All we need to do during the cell initialization
is to set the image and the tile.
www.letsnurture.com
www.letsnurture.com
class CustomTableViewCell :UITableViewCell {
@IBOutlet var backgroundImage:UIImageView
@IBOutlet var titleLabel:UILabel
func loadItem(#title: String, image:String) {
backgroundImage.image =UIImage(named:image)
titleLabel.text =title
}
}
www.letsnurture.com
For you Objective-C folks in Swift you do not need to call
properties using the self keyword! Use the self keyword
only when you have a parameter named like your
property, so that the compiler can understand your code.
Note: This function uses a shorthand external
parameter name.
If the method declaration was func loadItem(title: String, image:
String) (without # symbol) to call it we would have to
write cell.loadItem("We❤Swift", image: "someimage.jpeg").
Instead, with the # symbol, to call loadItem we would
write cell.loadItem(title: "We❤Swift", image: "someimage.jpeg").
Add some data to display
• Download the swifts and add them in your
project. Unarchive the zip file and drag the
files in you Xcode Navigator.
• Make sure to check Copy items if needed.
• For each custom cell we need a title and a
image name, we are going to store them in
an Array of Tuples.
www.letsnurture.com
www.letsnurture.com
The first value will represent the title and the second
one the imageName.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
...
var items:[(String, String)] = [
("❤", "swift 1.jpeg"),
("We", "swift 2.jpeg"),
("❤", "swift 3.jpeg"),
("Swift", "swift 4.jpeg"),
("❤", "swift 5.jpeg")
]
}
Set the number of rows
• Implement tableView(_:numberOfRowsInSection:) and return the number of
items.
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
...
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ->
Int {
return items.count;
}
}
• Note: In iOS the number of sections is 1 by default, so we do not need to set a
value for that. In case you want to create a table with multiple sections just
implement the numberOfSectionsInTableView(_:) method.
www.letsnurture.com
Register the Nib
Load the CustomTableViewCell interface file into a UINib object and then tell the table
view to use it for the customCell reuse identifier.
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
...
override func viewDidLoad() {
...
var nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "customCell")
}
...
}
www.letsnurture.com
Create the cell
• Now when you will ask for a cell from the table view with
the reuse identifier customCell, the tableView will look for
any unused cells with that reuse identifier or just create
one using the CustomTableViewCell nib.
• The tableView will call the
tableView(_:cellForRowAtIndexPath:) method on the
dataSource whenever it need a specific cell. The location of
the cell is stored in an NSIndexPath that has a row and
section property.
• To create a cell all we need to do is ask for one using the
dequeueReusableCellWithIdentifier(_:) method. After we
have a cell we need to load the title and image and then
return it.
www.letsnurture.com
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
...
func tableView(tableView: UITableView!, cellForRowAtIndexPath
indexPath: NSIndexPath!) -> UITableViewCell {
var cell:CustomTableViewCell =
self.tableView.dequeueReusableCellWithIdentifier("customCell") as
CustomTableViewCell
// this is how you extract values from a tuple
var (title, image) = items[indexPath.row]
cell.loadItem(title: title, image: image)
return cell
}
}
www.letsnurture.com
Handle Table Selection
• When a cell is selected the table view will call the
tableView(_:didSelectRowAtIndexPath:) method on the delegate.
• To handle table view selection all you need to do is implement that
method.
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
...
func tableView(tableView: UITableView!, didSelectRowAtIndexPath
indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
println("You selected cell #(indexPath.row)!")
}
}
www.letsnurture.com
Add a blur view
• In iOS 8 we now have a easy way of recreating
the blur effect used throughout the system.
UIVisualEffectView is a subclass ofUIView that
provides a simple abstraction over complex
visual effects.
• UIKit has two implemented effects
UIBlurEffect andUIVibrancyEffect.
• Let’s create a UIVisualEffectView and add it to
the main view.
www.letsnurture.com
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
...
override func viewDidLoad() {
...
addEffect()
...
}
func addEffect() {
var effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
var effectView = UIVisualEffectView(effect: effect)
effectView.frame = CGRectMake(0, 0, 320, 100)
view.addSubview(effectView)
}
...
}
www.letsnurture.com
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
...
override func viewDidLoad() {
super.viewDidLoad()
addEffect(UIBlurEffect(style: UIBlurEffectStyle.Light), offset: 0)
addEffect(UIBlurEffect(style: UIBlurEffectStyle.Dark), offset: 50)
addEffect(UIBlurEffect(style: UIBlurEffectStyle.ExtraLight), offset: 100)
var nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "customCell") }
func addEffect(effect: UIVisualEffect, offset: CGFloat) {
var effectView = UIVisualEffectView(effect: effect)
effectView.frame = CGRectMake(0, offset, 320, 50)
view.addSubview(effectView) }
...
}
www.letsnurture.com
www.letsnurture.com
There are 3 type of blur effects.
If we send the effect and offset as a parameters
to the addEffect method we can reuse the code
and see all three blur effects at once.
Extend the Array class
• In ruby the Array class two nifty
methods each and eachWithIndex.
• The each method takes a function as a parameter and
calls it with each element of the array in
order, eachWithIndex takes a function as a parameter
and calls it with the tuple (element, index)for each
element.
• We can extend a class using the extension keyword.
• The implementation of each and eachWithIndex in
Swift would look like this:
www.letsnurture.com
extension Array {
func each(callback: T -> ()) {
for item in self {
callback(item)
}
}
func eachWithIndex(callback: (T, Int) -> ()) {
var index = 0
for item in self {
callback(item, index)
index += 1
}
}
}
www.letsnurture.com
Putting it all together
Now we have 3 method calls that look pretty similar. Two things
change: the style and offset.
override func viewDidLoad() {
...
addEffect(UIBlurEffect(style: UIBlurEffectStyle.Light), offset: 0)
addEffect(UIBlurEffect(style: UIBlurEffectStyle.Dark), offset: 50)
addEffect(UIBlurEffect(style: UIBlurEffectStyle.ExtraLight),
offset: 100)
...
}
www.letsnurture.com
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
...
override func viewDidLoad() {
...
addEffects()
...
}
func addEffects() {
[
UIBlurEffect(style: UIBlurEffectStyle.Light),
UIBlurEffect(style: UIBlurEffectStyle.Dark),
UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)
].eachWithIndex { (effect, index) in
var effectView = UIVisualEffectView(effect: effect)
effectView.frame = CGRectMake(0, CGFloat(50 * index), 320, 50)
self.view.addSubview(effectView)
}
}
...
}
www.letsnurture.com
We can do one thing here and use the map function:
func addEffects() {
[
UIBlurEffectStyle.Light,
UIBlurEffectStyle.Dark,
UIBlurEffectStyle.ExtraLight
].map {
UIBlurEffect(style: $0)
}.eachWithIndex { (effect, index) in
var effectView = UIVisualEffectView(effect: effect)
effectView.frame = CGRectMake(0, CGFloat(50 * index), 320, 50)
self.view.addSubview(effectView)
}
} www.letsnurture.com
Challenges:
• use more than one type of cell in the same table
view
• implement more of the dataSource and delegate
methods and see what you can do with them.
You could start
withnumberOfSectionsInTableView(_:),
tableView(_:titleForHeaderInSection:),
sectionIndexTitlesForTableView(_:),tableView(_:h
eightForRowAtIndexPath:)
• make a Contact Book App (hint: finish the second
challenge first)
www.letsnurture.com
Follow us on
https://www.facebook.com/LetsNurture
https://twitter.com/letsnurture
http://www.linkedin.com/company/letsnurture
Mail Us on
info@letsnurture.om
www.letsnurture.com | www.letsnurture.co.uk

More Related Content

What's hot

Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data BindingEric Maxwell
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swingNataraj Dg
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2stuq
 
A to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperA to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperManoj Bhuva
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptmartinlippert
 
Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone
Tutorial on Creating an iOS SQLite Database Application | iOS | iPhoneTutorial on Creating an iOS SQLite Database Application | iOS | iPhone
Tutorial on Creating an iOS SQLite Database Application | iOS | iPhonechunkyhuman7962
 
Building Reusable Custom Elements With Angular
Building Reusable Custom Elements With AngularBuilding Reusable Custom Elements With Angular
Building Reusable Custom Elements With AngularIlia Idakiev
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.UA Mobile
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial추근 문
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetimdurgesh
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageRonald Ashri
 
Swiftとメソッドのアレコレ
SwiftとメソッドのアレコレSwiftとメソッドのアレコレ
SwiftとメソッドのアレコレNobuo Saito
 
iOS Contact List Application Tutorial
iOS Contact List Application TutorialiOS Contact List Application Tutorial
iOS Contact List Application TutorialIshara Amarasekera
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUIAdam Lu
 

What's hot (20)

Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data Binding
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swing
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
 
Ms Ajax Dom Element Class
Ms Ajax Dom Element ClassMs Ajax Dom Element Class
Ms Ajax Dom Element Class
 
A to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperA to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java Developer
 
I os 04
I os 04I os 04
I os 04
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScript
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone
Tutorial on Creating an iOS SQLite Database Application | iOS | iPhoneTutorial on Creating an iOS SQLite Database Application | iOS | iPhone
Tutorial on Creating an iOS SQLite Database Application | iOS | iPhone
 
Building Reusable Custom Elements With Angular
Building Reusable Custom Elements With AngularBuilding Reusable Custom Elements With Angular
Building Reusable Custom Elements With Angular
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
 
Solid angular
Solid angularSolid angular
Solid angular
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheet
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of Usage
 
Swiftとメソッドのアレコレ
SwiftとメソッドのアレコレSwiftとメソッドのアレコレ
Swiftとメソッドのアレコレ
 
Session 2 django material for training at baabtra models
Session 2 django material for training at baabtra modelsSession 2 django material for training at baabtra models
Session 2 django material for training at baabtra models
 
Backbone js
Backbone jsBackbone js
Backbone js
 
iOS Contact List Application Tutorial
iOS Contact List Application TutorialiOS Contact List Application Tutorial
iOS Contact List Application Tutorial
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 

Viewers also liked

Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app developmentopenak
 
The Swift Programming Language with iOS App
The Swift Programming Language with iOS AppThe Swift Programming Language with iOS App
The Swift Programming Language with iOS AppMindfire Solutions
 
Medidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium HighlightsMedidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium HighlightsDonna Locke
 
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08Dennis Sweitzer
 
Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013Brock Heinz
 
Tools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOSTools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOSTeri Grossheim
 
Swift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structureSwift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structureKwang Woo NAM
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)Jonathan Engelsma
 
Beginning iOS Development with Swift
Beginning iOS Development with SwiftBeginning iOS Development with Swift
Beginning iOS Development with SwiftTurnToTech
 
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageHossam Ghareeb
 
I os swift 3.0 初體驗 & 玩 facebook sdk
I os swift 3.0 初體驗 & 玩 facebook sdkI os swift 3.0 初體驗 & 玩 facebook sdk
I os swift 3.0 初體驗 & 玩 facebook sdk政斌 楊
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOSMake School
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core DataMake School
 
iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉政斌 楊
 
How to create edit checks in medidata rave painlessly
How to create edit checks in medidata rave painlesslyHow to create edit checks in medidata rave painlessly
How to create edit checks in medidata rave painlesslyWeihong Yang
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageHossam Ghareeb
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.Icalia Labs
 

Viewers also liked (20)

Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app development
 
The Swift Programming Language with iOS App
The Swift Programming Language with iOS AppThe Swift Programming Language with iOS App
The Swift Programming Language with iOS App
 
iOSMumbai Meetup Keynote
iOSMumbai Meetup KeynoteiOSMumbai Meetup Keynote
iOSMumbai Meetup Keynote
 
Medidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium HighlightsMedidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium Highlights
 
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
 
Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013
 
Tools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOSTools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOS
 
Medidata Rave Coder
Medidata Rave CoderMedidata Rave Coder
Medidata Rave Coder
 
Swift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structureSwift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structure
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
 
Beginning iOS Development with Swift
Beginning iOS Development with SwiftBeginning iOS Development with Swift
Beginning iOS Development with Swift
 
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming language
 
I os swift 3.0 初體驗 & 玩 facebook sdk
I os swift 3.0 初體驗 & 玩 facebook sdkI os swift 3.0 初體驗 & 玩 facebook sdk
I os swift 3.0 初體驗 & 玩 facebook sdk
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Developing iOS apps with Swift
Developing iOS apps with SwiftDeveloping iOS apps with Swift
Developing iOS apps with Swift
 
iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉
 
How to create edit checks in medidata rave painlessly
How to create edit checks in medidata rave painlesslyHow to create edit checks in medidata rave painlessly
How to create edit checks in medidata rave painlessly
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
 

Similar to Swift Tableview iOS App Development

Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsallanh0526
 
Say bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & KotlinSay bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & KotlinMiquel Beltran Febrer
 
Different types of sticker apps
Different types of sticker appsDifferent types of sticker apps
Different types of sticker appsJelena Krmar
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSAkshay Mathur
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsDiego Grancini
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library 10Clouds
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsTonny Madsen
 
iOS Beginners Lesson 2
iOS Beginners Lesson 2iOS Beginners Lesson 2
iOS Beginners Lesson 2Calvin Cheng
 
Cocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollersCocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollersStijn Willems
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84Mahmoud Samir Fayed
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Manykenatmxm
 

Similar to Swift Tableview iOS App Development (20)

Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Say bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & KotlinSay bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & Kotlin
 
IOS Storyboards
IOS StoryboardsIOS Storyboards
IOS Storyboards
 
Different types of sticker apps
Different types of sticker appsDifferent types of sticker apps
Different types of sticker apps
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
 
iOS
iOSiOS
iOS
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
 
I os 11
I os 11I os 11
I os 11
 
iOS Beginners Lesson 2
iOS Beginners Lesson 2iOS Beginners Lesson 2
iOS Beginners Lesson 2
 
Cocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollersCocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollers
 
201104 iphone navigation-based apps
201104 iphone navigation-based apps201104 iphone navigation-based apps
201104 iphone navigation-based apps
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
IOS APPs Revision
IOS APPs RevisionIOS APPs Revision
IOS APPs Revision
 

More from Ketan Raval

Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)Ketan Raval
 
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...Ketan Raval
 
Zero ui future is here
Zero ui   future is hereZero ui   future is here
Zero ui future is hereKetan Raval
 
Android n and beyond
Android n and beyondAndroid n and beyond
Android n and beyondKetan Raval
 
IoT and Future of Connected world
IoT and Future of Connected worldIoT and Future of Connected world
IoT and Future of Connected worldKetan Raval
 
#Instagram API Get visibility you always wanted
#Instagram API   Get visibility you always wanted#Instagram API   Get visibility you always wanted
#Instagram API Get visibility you always wantedKetan Raval
 
Keynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG AhmedabadKeynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG AhmedabadKetan Raval
 
Android notifications
Android notificationsAndroid notifications
Android notificationsKetan Raval
 
How to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA CompliantHow to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA CompliantKetan Raval
 
3 d touch a true game changer
3 d touch a true game changer3 d touch a true game changer
3 d touch a true game changerKetan Raval
 
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel EconomyOBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel EconomyKetan Raval
 
Vehicle to vehicle communication using gps
Vehicle to vehicle communication using gpsVehicle to vehicle communication using gps
Vehicle to vehicle communication using gpsKetan Raval
 
Obd how to guide
Obd how to guideObd how to guide
Obd how to guideKetan Raval
 
Garmin api integration
Garmin api integrationGarmin api integration
Garmin api integrationKetan Raval
 
Beacon The Google Way
Beacon The Google WayBeacon The Google Way
Beacon The Google WayKetan Raval
 
Edge detection iOS application
Edge detection iOS applicationEdge detection iOS application
Edge detection iOS applicationKetan Raval
 
Google calendar integration in iOS app
Google calendar integration in iOS appGoogle calendar integration in iOS app
Google calendar integration in iOS appKetan Raval
 
Big data cloudcomputing
Big data cloudcomputingBig data cloudcomputing
Big data cloudcomputingKetan Raval
 
All about Apple Watchkit
All about Apple WatchkitAll about Apple Watchkit
All about Apple WatchkitKetan Raval
 

More from Ketan Raval (20)

Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)
 
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
 
Keynote 2016
Keynote 2016Keynote 2016
Keynote 2016
 
Zero ui future is here
Zero ui   future is hereZero ui   future is here
Zero ui future is here
 
Android n and beyond
Android n and beyondAndroid n and beyond
Android n and beyond
 
IoT and Future of Connected world
IoT and Future of Connected worldIoT and Future of Connected world
IoT and Future of Connected world
 
#Instagram API Get visibility you always wanted
#Instagram API   Get visibility you always wanted#Instagram API   Get visibility you always wanted
#Instagram API Get visibility you always wanted
 
Keynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG AhmedabadKeynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG Ahmedabad
 
Android notifications
Android notificationsAndroid notifications
Android notifications
 
How to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA CompliantHow to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA Compliant
 
3 d touch a true game changer
3 d touch a true game changer3 d touch a true game changer
3 d touch a true game changer
 
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel EconomyOBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
 
Vehicle to vehicle communication using gps
Vehicle to vehicle communication using gpsVehicle to vehicle communication using gps
Vehicle to vehicle communication using gps
 
Obd how to guide
Obd how to guideObd how to guide
Obd how to guide
 
Garmin api integration
Garmin api integrationGarmin api integration
Garmin api integration
 
Beacon The Google Way
Beacon The Google WayBeacon The Google Way
Beacon The Google Way
 
Edge detection iOS application
Edge detection iOS applicationEdge detection iOS application
Edge detection iOS application
 
Google calendar integration in iOS app
Google calendar integration in iOS appGoogle calendar integration in iOS app
Google calendar integration in iOS app
 
Big data cloudcomputing
Big data cloudcomputingBig data cloudcomputing
Big data cloudcomputing
 
All about Apple Watchkit
All about Apple WatchkitAll about Apple Watchkit
All about Apple Watchkit
 

Recently uploaded

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Recently uploaded (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Swift Tableview iOS App Development

  • 2. www.letsnurture.com Create a new project Open Xcode 6, create a new “Single Page Application” and select Swift as the programming language.
  • 3. Add a table view property • Open the ViewController.swift class and add a new tableview instance variable below the class declaration. • Add the @IBOutletInterface Builder declaration attribute to expose the tableView property. • “Interface Builder attributes are declaration attributes used by Interface Builder to synchronize with Xcode. Swift provides the following Interface Builder attributes: IBAction, IBDesignable, IBInspectable, and IBOutlet. These attributes are conceptually the same as their Objective-C counterparts.” www.letsnurture.com
  • 4. www.letsnurture.com class ViewController: UIViewController { @IBOutlet var tableView: UITableView ... }
  • 5. www.letsnurture.com Conform to the UITableViewDelegate and UITableViewDataSource protocols To conform to the UITableViewDelegate and UITableViewDataSource protocol, just add them separated by commas afterUIViewController in the class declaration. (more about protocols in Apple’s Docs) class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... }
  • 6. www.letsnurture.com Add a table view in your view controller interface Open Main.storyboard and drag a UITableView from the library (in the lower right corner) into the ViewController view.
  • 7. www.letsnurture.com Connect the Interface Builder outlets Connect the dataSource, delegate and tableView outlets in interface builder. Just right click on the table view and then connect them
  • 8. www.letsnurture.com Create the custom cell class Create a new class above your ViewController code. Your custom cell class should inherit from UITableViewCell! Add outlets for the backgroundImage and titleLabel. class CustomTableViewCell : UITableViewCell { @IBOutlet var backgroundImage:UIImageView @IBOutlet var titleLabel: UILabel } class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... }
  • 9. www.letsnurture.com Create the custom cell interface Right click on your applications directory and select new file.
  • 10. www.letsnurture.com Select User Interface and then the Empty template. Select iPhone and name it CustomTableViewCell. Open CustomTableViewCell.xib and add a UITableViewCell in it from the component library. Select the Table View Cell and change it’s class to CustomTableViewCell
  • 11. www.letsnurture.com After that the table view cell should change its name to Custom Table View Cell, the backgroundImage and titleLabel outlets should be visible now. Add an image view and a label in the cell. Resize the cell to 320 x 320 using the size inspector. And set the row height to 320
  • 12. www.letsnurture.com Connect the cell outlets to the CustomTableCellViewCell. Notice that custom view bind outlets to the view object and custom view controllers bind them to the File's Owner
  • 13. Add the loadItem method • In a real life application you usualy have more than one type of cell in a table view (or collection view). • By keeping the initialization logic in the cell we can avoid code duplication or spaghetti code. • This cell displays an image stored on the device and has a string title. • All we need to do during the cell initialization is to set the image and the tile. www.letsnurture.com
  • 14. www.letsnurture.com class CustomTableViewCell :UITableViewCell { @IBOutlet var backgroundImage:UIImageView @IBOutlet var titleLabel:UILabel func loadItem(#title: String, image:String) { backgroundImage.image =UIImage(named:image) titleLabel.text =title } }
  • 15. www.letsnurture.com For you Objective-C folks in Swift you do not need to call properties using the self keyword! Use the self keyword only when you have a parameter named like your property, so that the compiler can understand your code. Note: This function uses a shorthand external parameter name. If the method declaration was func loadItem(title: String, image: String) (without # symbol) to call it we would have to write cell.loadItem("We❤Swift", image: "someimage.jpeg"). Instead, with the # symbol, to call loadItem we would write cell.loadItem(title: "We❤Swift", image: "someimage.jpeg").
  • 16. Add some data to display • Download the swifts and add them in your project. Unarchive the zip file and drag the files in you Xcode Navigator. • Make sure to check Copy items if needed. • For each custom cell we need a title and a image name, we are going to store them in an Array of Tuples. www.letsnurture.com
  • 17. www.letsnurture.com The first value will represent the title and the second one the imageName. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... var items:[(String, String)] = [ ("❤", "swift 1.jpeg"), ("We", "swift 2.jpeg"), ("❤", "swift 3.jpeg"), ("Swift", "swift 4.jpeg"), ("❤", "swift 5.jpeg") ] }
  • 18. Set the number of rows • Implement tableView(_:numberOfRowsInSection:) and return the number of items. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count; } } • Note: In iOS the number of sections is 1 by default, so we do not need to set a value for that. In case you want to create a table with multiple sections just implement the numberOfSectionsInTableView(_:) method. www.letsnurture.com
  • 19. Register the Nib Load the CustomTableViewCell interface file into a UINib object and then tell the table view to use it for the customCell reuse identifier. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... override func viewDidLoad() { ... var nib = UINib(nibName: "CustomTableViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: "customCell") } ... } www.letsnurture.com
  • 20. Create the cell • Now when you will ask for a cell from the table view with the reuse identifier customCell, the tableView will look for any unused cells with that reuse identifier or just create one using the CustomTableViewCell nib. • The tableView will call the tableView(_:cellForRowAtIndexPath:) method on the dataSource whenever it need a specific cell. The location of the cell is stored in an NSIndexPath that has a row and section property. • To create a cell all we need to do is ask for one using the dequeueReusableCellWithIdentifier(_:) method. After we have a cell we need to load the title and image and then return it. www.letsnurture.com
  • 21. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell { var cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell // this is how you extract values from a tuple var (title, image) = items[indexPath.row] cell.loadItem(title: title, image: image) return cell } } www.letsnurture.com
  • 22. Handle Table Selection • When a cell is selected the table view will call the tableView(_:didSelectRowAtIndexPath:) method on the delegate. • To handle table view selection all you need to do is implement that method. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { tableView.deselectRowAtIndexPath(indexPath, animated: true) println("You selected cell #(indexPath.row)!") } } www.letsnurture.com
  • 23. Add a blur view • In iOS 8 we now have a easy way of recreating the blur effect used throughout the system. UIVisualEffectView is a subclass ofUIView that provides a simple abstraction over complex visual effects. • UIKit has two implemented effects UIBlurEffect andUIVibrancyEffect. • Let’s create a UIVisualEffectView and add it to the main view. www.letsnurture.com
  • 24. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... override func viewDidLoad() { ... addEffect() ... } func addEffect() { var effect = UIBlurEffect(style: UIBlurEffectStyle.Light) var effectView = UIVisualEffectView(effect: effect) effectView.frame = CGRectMake(0, 0, 320, 100) view.addSubview(effectView) } ... } www.letsnurture.com
  • 25. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... override func viewDidLoad() { super.viewDidLoad() addEffect(UIBlurEffect(style: UIBlurEffectStyle.Light), offset: 0) addEffect(UIBlurEffect(style: UIBlurEffectStyle.Dark), offset: 50) addEffect(UIBlurEffect(style: UIBlurEffectStyle.ExtraLight), offset: 100) var nib = UINib(nibName: "CustomTableViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: "customCell") } func addEffect(effect: UIVisualEffect, offset: CGFloat) { var effectView = UIVisualEffectView(effect: effect) effectView.frame = CGRectMake(0, offset, 320, 50) view.addSubview(effectView) } ... } www.letsnurture.com
  • 26. www.letsnurture.com There are 3 type of blur effects. If we send the effect and offset as a parameters to the addEffect method we can reuse the code and see all three blur effects at once.
  • 27. Extend the Array class • In ruby the Array class two nifty methods each and eachWithIndex. • The each method takes a function as a parameter and calls it with each element of the array in order, eachWithIndex takes a function as a parameter and calls it with the tuple (element, index)for each element. • We can extend a class using the extension keyword. • The implementation of each and eachWithIndex in Swift would look like this: www.letsnurture.com
  • 28. extension Array { func each(callback: T -> ()) { for item in self { callback(item) } } func eachWithIndex(callback: (T, Int) -> ()) { var index = 0 for item in self { callback(item, index) index += 1 } } } www.letsnurture.com
  • 29. Putting it all together Now we have 3 method calls that look pretty similar. Two things change: the style and offset. override func viewDidLoad() { ... addEffect(UIBlurEffect(style: UIBlurEffectStyle.Light), offset: 0) addEffect(UIBlurEffect(style: UIBlurEffectStyle.Dark), offset: 50) addEffect(UIBlurEffect(style: UIBlurEffectStyle.ExtraLight), offset: 100) ... } www.letsnurture.com
  • 30. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... override func viewDidLoad() { ... addEffects() ... } func addEffects() { [ UIBlurEffect(style: UIBlurEffectStyle.Light), UIBlurEffect(style: UIBlurEffectStyle.Dark), UIBlurEffect(style: UIBlurEffectStyle.ExtraLight) ].eachWithIndex { (effect, index) in var effectView = UIVisualEffectView(effect: effect) effectView.frame = CGRectMake(0, CGFloat(50 * index), 320, 50) self.view.addSubview(effectView) } } ... } www.letsnurture.com
  • 31. We can do one thing here and use the map function: func addEffects() { [ UIBlurEffectStyle.Light, UIBlurEffectStyle.Dark, UIBlurEffectStyle.ExtraLight ].map { UIBlurEffect(style: $0) }.eachWithIndex { (effect, index) in var effectView = UIVisualEffectView(effect: effect) effectView.frame = CGRectMake(0, CGFloat(50 * index), 320, 50) self.view.addSubview(effectView) } } www.letsnurture.com
  • 32. Challenges: • use more than one type of cell in the same table view • implement more of the dataSource and delegate methods and see what you can do with them. You could start withnumberOfSectionsInTableView(_:), tableView(_:titleForHeaderInSection:), sectionIndexTitlesForTableView(_:),tableView(_:h eightForRowAtIndexPath:) • make a Contact Book App (hint: finish the second challenge first) www.letsnurture.com