33
Swift Tableview www.letsnurture.com

Swift Tableview iOS App Development

Embed Size (px)

Citation preview

Swift Tableview

www.letsnurture.com

www.letsnurture.com

Create a new projectOpen 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 interfaceOpen 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 classCreate 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 interfaceRight 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!, cellForRowAtIndexPathindexPath: 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!, didSelectRowAtIndexPathindexPath: 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 = 0for item in self {

callback(item, index)index += 1

}}

}

www.letsnurture.com

Putting it all togetherNow 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(_:heightForRowAtIndexPath:)

• 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 [email protected]

www.letsnurture.com | www.letsnurture.co.uk