• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • About
  • Portfolio
  • Privacy Policy

Archives for March 2016

How to increase number of worksheets Excel

March 18, 2016 By Ravi Shankar Leave a Comment

Microsoft Excel by default contains 3 worksheets while creating a new Workbook. For creating a new workbook you can specify the number of Worksheet that a Workbook needs to contain. This can be modified using Excel Options. Listed below are steps for increasing number of Worksheets for a new Workbook in Excel 2013, Excel 2010 and Excel 2007

In Excel 2013 and Excel 2010 –> Click on File menu and then Options.

increase sheets in Workbook in Excel 2013

In Excel 2007 –> Click on Excel Options and then Popular menu.

Excel Options in Excel 2007

Increase worksheets for new workbook in Excel 2007

Under When creating new workbooks section there is include this many sheets fields. This can be used for increasing the number worksheets while creating a new workbook. The minimum value is 1 and the maximum is 255. Check out the below video demo to increase worksheets size in Excel 2013

Also See: How to move or copy worksheets in Excel 2013

Filed Under: Excel, Excel 2007, Excel 2010, Excel 2013, Office 2007, Office 2010, Office 2013 Tagged With: Decrease sheets, increase sheets, Workbook, Worksheets Size

UITableView Demo in Swift

March 10, 2016 By Ravi Shankar 2 Comments

In this tutorial, we will see some of the common UITableView operations such as Adding, Updating, Deleting and Moving records using Swift.

Let us start with a TableView placed over a ViewController instead of using UITableViewController. By this way you will learn lot more about the functionality of UITableView. Add a new file and select Cocoa Touch Class as a template for the new file.

In “Choose options for your new file” screen, enter the class name as TableViewDemoController with subclass as UIViewController. Then save the new file under your preferred location.

User Interface

Navigate to Main.stotyboard then drag and drop a ViewController from Object Libray to Storyboard. Select the ViewController and click Show Identity Inspection and enter the class name as “TableViewDemoController”

Drag and drop Table View from object library to the View Controlller and make sure Table View is aligned properly. Now place a Table View Cell from object library on top of the TableView.

Set the identifier for Prototype cell to “CellIdentifier” using Show Identity Inspector.

Now select the tableview in the Document Outline pane and click Connection Inspector under Utilies pane. Connect the dataSource and delegate Outlets to the TableViewDemoController (yellow color circle on top View Controller)

Display Data

In this demo, we will be seeing how to display list of Socia Media icons. Here are the steps to load those icons in TableView.

First create a Struct that would act as a place holder for holding the name and image file name. Right click on the Project, select New File. In template screen, choose Swift file and provide name as SocialMedia and save the file.

Edit SocialMedia.swift and add the following code snippet. Apart name and imageName property, this also has computed property that returms UIImage based upon the image file name.

import UIKit

struct SocialMedia {

    var name:String
    var imageName:String
    var image: UIImage {
        get {
            return UIImage(named: imageName)!
        }
    }

}

Now Drag and drop social icon images from folder to Xcode project (download images from gitHub repoistory). Navigate TableViewDemoController.swift and add the following code snippet.

var data:[SocialMedia] = [SocialMedia]()

//MARK:- Populate data   

    func loadData() -> [SocialMedia] {

        data.append(SocialMedia(name:"Evernote",imageName:"evernote"))
        data.append(SocialMedia(name:"Facebook",imageName:"facebook"))
        data.append(SocialMedia(name:"GitHub",imageName:"github"))
        data.append(SocialMedia(name:"Google",imageName:"google"))
        data.append(SocialMedia(name:"LinkedIn",imageName:"linkedin"))
        data.append(SocialMedia(name:"Paypal",imageName:"paypal"))
        data.append(SocialMedia(name:"Pinterest",imageName:"pinterest"))
        data.append(SocialMedia(name:"Twitter",imageName:"twitter"))
        data.append(SocialMedia(name:"Vimeo",imageName:"vimeo"))
        data.append(SocialMedia(name:"YouTube",imageName:"youtube"))

        return data
    }

We have declared an array called data which will hold all the SocialMedia icon related information. The function loadData is used for adding all the social media images. Now call this function in the viewDidLoad method.

override func viewDidLoad() {
	super.viewDidLoad()
	 // call loaddata
	 loadData()
 }

In order display data, ViewController needs to conform UITableViewDataSource protocol. Add UITableViewDataSource to the class declaration next to UIViewController.

class TableViewDemoController: UIViewController, UITableViewDataSource {

Then implement the following methods in TableViewDemoController class, these required methods when a class conforms to UITableViewDataSource protocol.

extension TableViewDemoController: UITableViewDataSource {

    // MARK:- TabvleView dataSource methods

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(IDENTIFIER,
            forIndexPath: indexPath)

        let socialMedia = data[indexPath.row]

        cell.textLabel?.text = socialMedia.name

        cell.imageView?.image = socialMedia.image

        return cell
    }
}

Finally we need to create IBOutlet for tableView and connect with tableView control in Storyboard.

@IBOutlet var tableView: UITableView!

Now you should be able to build and run the project. This should show list all Social Media icons as shown below

Customize UITableView

In order the customize the tableview, the TableViewDemoController class needs to conform to UITableViewDelegate protocol. Let us say you want to increase the height of tableview rows. Then implement the function heightForRowAtIndexPath to return the height for each row.

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
	return 60.0
}

Build and run the project should show the difference in height.

Add and Update row

Navigate to Main.storyboard and add a new View Controller to Interface builder. This View Controller will be used for capturing name of the icon when adding a new row.

This View Controller has a text field to accept the name of the Social Media icon, Done button to save the entered informatiom and Cancel button to cancel the operation. Make sure to create Unwind segue for Done and Cancel button by Control drag and drop each button to Exit icon on the View Controller. Also provide the identifer for the Unwind segue as addAction and cancelAction.

Navigate to TableViewDemoController and add Bar Button Item to the left hand side. Set the Identifier of Bar Button Item to Add.

Now Control + Drag from the Add button to DetailViewController and select Segue as Push with identifier as “addAction”. Similarly to allow users to edit the existing row, Control + Drag TableView prototype cell to DetailViewController and set identifier for the Push segue as “editAction”.

Add a new Cocoa Touch Class file to the existing project with Sub class as UIViewController and name of the file as DetailViewController. Set this file as the class name in the Identity Inspector of DetailViewController in Interface builder.

Update the DetailViewController.swift and replace the existing code with the following lines of code.

import UIKit

class DetailViewController: UIViewController {

    var socialMedia: SocialMedia?

    @IBOutlet var textFeild:UITextField?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let name = socialMedia?.name {
            textFeild?.text = name
        }
    }

    // MARK:- PrepareForSegue

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        let name = textFeild?.text
        if var _ = socialMedia {
            self.socialMedia?.name = name!
        } else {
            socialMedia = SocialMedia(name:name!,imageName:"unknown")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

We have declared two variables socialMedia and index which will be populated when user taps an esitsing row in the TableView. Also you should find a IBOutlet for UITextField, make sure to connect this with TextField in the Interface Builder.

In the viewDidLoad function, if the user is editing an existing row then the textfield is updated with that value. The prepareForSegue method is called when the user taps Done or Cancel button. And based on the action, a new social media icon is added or an existing row is updated.

Navigate back to TableViewDemoController and implement the following function that will be called on cancel or done operation in DetailViewController.

//MARK:- Cancel and Done

    @IBAction func cancel(segue:UIStoryboardSegue) {
        // do nothing
    }

    @IBAction func done(segue:UIStoryboardSegue) {

        let detailViewController = segue.sourceViewController as!
        DetailViewController

        let socialMedia = detailViewController.socialMedia

        if let selectedIndex = index {
            data[selectedIndex] = socialMedia!
        } else {
            data.append(socialMedia!)
        }
        tableView.reloadData()
    }

Delete and Move row

Delete operation can be added by implementing the following function in TableViewDemoController.

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
	  switch editingStyle {
		case .Delete:
		// remove the deleted item from the model
	 	data.removeAtIndex(indexPath.row)
 		// remove the deleted item from the `UITableView`
		self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
	   	default:
		 return
   	}
}

This would allow users to swipe and delete a row in TableView. The function checks whether the editing style is Delete, then the row is removed from the array as well from the TableView display.

In order to allow users to move the rows, the tableView editing property needs to be set to true. Add another Bar Button Item, this time to the right of TableViewDemoController and provide the caption as Edit. Then connect this button with the following IBAction function.

//MARK:- Editing toggle

This button acts as a toggle switch to enable or disable tableview edit operation. Now add the following function required for Move operation.

//MARK:- TableViewCell Move row methods
	func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
     	return true
    }

Function canMoveRowAtIndexPath needs to return true and in moveRowAtIndexPath function, the tableView row data gets removed from the original index and inserted in to the new position.

Now the user can tap and hold the move option then drag and drop it to the desired position. When the tableview editing is set to true, it also provides delete button apart from the move operation.

Download the source code from here.

Social Media icons credit to Sebastiano Guerriero

Filed Under: Uncategorized

Protocol Oriented Programming in Swift

March 10, 2016 By Ravi Shankar Leave a Comment

Object Oriented Programming is a paradigm used by programmers many decaded to solve computer problems by modeling them in to classes. In Swift 2.0 a new programming pattern has been introduced known as Protocol Oriented Programming. In this article, we will the three major feature as part of Protocol Oriented Programming

  • Modeling with Protocols and Structs
  • Protocol Extension
  • Swift Standard Library Extension

Using Protocols and Structs

Let us see an example by modeling Bicylce, MotorBike and Car with Protocols and Structs. Create Vehicle and MotorVehicle protocol with the following property definition

[code language=”swift”]protocol Vehicle {
var speed: Int {get}
var color: String {get}
var yearOfMake: Int {get}
}

protocol MotorVehicle {
var engineSize: Int {get}
var licensePlate: String {get}
}
[/code]

In Swift we can make any type (Class. Struct, Enums) to conform to a Protocol. Let us go for a value type (Struct) and not class as we are moving away from inheritance. And it is always safe to use value type and avoid memory related issues by using object references (Class).

[code language=”swift”]struct Bicyle: Vehicle {
let speed: Int
let color: String
let yearOfMake: Int
}

struct MotorBike: MotorVehicle, Vehicle {
let speed: Int
let color: String
let engineSize: Int
let licensePlate: String
let yearOfMake: Int
}
struct Car: MotorVehicle, Vehicle {
let speed: Int
let color: String
let engineSize: Int
let licensePlate: String
let numberOfDoors: Int
let yearOfMake: Int
}[/code]

In the above code snippet, we have created three strutcs Bicycle, MotorBike and Car. Bicyle conforms to Vehicle but Car and MotorBike conform to both Vehicle and MotorVehicle. Now start creating Cars, Bicycles and MotorBikes using corresponding structs.

[code language=”swift”]let cycle = Bicyle(speed: 10, color: “Blue”,yearOfMake: 2011)
let bike = MotorBike(speed: 65, color: “Red”, engineSize: 100, licensePlate: “HT-12345”,yearOfMake: 2015)
let bmw = Car(speed: 220, color: “Green”, engineSize: 1200, licensePlate: “FC-20 435”, numberOfDoors: 4,yearOfMake: 2016)
let audi = Car(speed: 220, color: “Cyan”, engineSize: 1200, licensePlate: “FC-41 234”, numberOfDoors: 4,yearOfMake: 2013)
[/code]

Protocol Extension

In Swift 2.0, the real power Protocol comes with its ability to add extension. It is not just adding method definition but now Protocol allows you to add implemenation as well. Let us say you want to compare vehicles based on yearOfMake attribute. All you need to do is to add an extension for Vehicle Protocol

[code language=”swift”]extension Vehicle {
func isNewer(item: Vehicle) -> Bool {
return self.yearOfMake > item.yearOfMake
}
}
// comparing audi and bmw should return false
audi.isNewer(bmw)[/code]

Swift Standard Library Extension

You can also add extension to Swift standard library such CollectionType, Range, Array etc.. Let us take the following scenario where you have an array of MotorBikes and want to filter them based on licensePlate information.

[code language=”swift”]let bike1 = MotorBike(speed: 65, color: “Red”, engineSize: 100, licensePlate: “HT-12345”,yearOfMake: 2015)
let bike2 = MotorBike(speed: 75, color: “Black”, engineSize: 120, licensePlate: “RV-453”,yearOfMake: 2013)
let bike3 = MotorBike(speed: 55, color: “Blue”, engineSize: 80, licensePlate: “XY-5 520”,yearOfMake: 2012)
let bike4 = MotorBike(speed: 55, color: “Red”, engineSize: 80, licensePlate: “XY-7 800”,yearOfMake: 2009)

let motorbikes = [bike1,bike2, bike3, bike4]
[/code]

How about filtering of all Small Mopeds based on licensePlate containing “XY” characters. This can be achieved by adding an extension to CollectionType which conforms to MotorVehicle protocol. Then create a new function “filterLicensePlate” as shown below

[code language=”swift”]extension CollectionType where Generator.Element:MotorVehicle {
func filterLicensePlate(match:String -> [Generator.Element] {
var result:[Generator.Element] = []
for item in self {
if item.licensePlate.containsString(match) {
result.append(item)
}
}
return result
}
} [/code][code language=”swift”]let motorbikes = [bike1,bike2, bike3, bike4]
// fiter only small mopeds based on XY
motorbikes.filterLicensePlate(“XY”).count
[/code]

Hope you found this introduction to Protocol Oriented Programming useful. Please use the comment section to add your feedback/suggestion.

References

WWDC 2015 – Protocol Oriented Programming
Mixing and Traits in Swift 2.0
Protocol-Oriented Programming in Swift 2
Introducing Protocol-Oriented Programming in Swift 2

Filed Under: Swift 2 Tagged With: Protocol, Protocol Oriented Programming, Struct

Content Priority in Auto Layout

March 4, 2016 By Ravi Shankar 1 Comment

Auto Layout brings in lots of good features to ease the life of an iOS developer when designing User Interfaces. In this example, we will see how to use Content Priorities such as Content Hugging and Comrpession Resistance.

I have created a project with Single View Template and dispayed Size Classes as we are going to focus only on iPhone family.

Drag and drop two labels adjacent to each other.

Add Leading Space and Vertical Space constraints for Label A. Similarly add Vertical Space and Trailing Space constraints for Label B

 

Constraints for Label A

Constraints for Label B

Click the Update Frames option under the Resolve AutoLayout Issues menu. This should align the frames to reflect the constraints changes.

Change the background colour of Labels to Yellow and Green respectively. This would help us to identity the growth of each labels. Now add the Horizontal Spacing constraint between these two labels and set constant to 5.

Now Label B has grown and covered the space between both labels. Please note that this would be in random nature some times even Label A can fill up the space between these labels. And in this article, we will see how to control this behaviour. You will also notice the warning message that “2 views are horizontally ambitguous”. This is because Auto Layout does not know which label should grow and shrink in size.

Content Compression Resistance Priority

Let us change the text for Label in left hand side as “Content Hugging”. Simialrly enter the text for right hand side label as “Compression Resistance”. Then Update Frames to refelect the Intrinsic Content Size changes. You will notice that the Compression Resistance has a truncated trail.

If you want to this label to resist shrinking its size then set the Content Compression Resistance Priority (Under Size Inspector) to value higher than the label on left hand side.

After changing the value from 750 to 751, you will notice the warning messages “Frame will be different at run time”. Now Updating the Frames for All Views in Container shoud reflect as shown in the below screenshot.

Content Hugging Priority

Now Content Hugging label is partially hidden and it cannot grow horizontally as right hand side label has a higher compression resistance priority. Let us set the number of lines for this lable to 0 (which means it can grow based on the content size). This should again result in “Content Priority Ambiguity” error. This time we can fix this by telling Auto Layout that the label on left hand side has least resistance for growth. Select the label on left hand side, navigate to Size Inspector and set the Content Hugging Priority to lower than right hand side label i.e from 251 to 250.

Click Update Frames to resolve the warning message “Frame for Content Hugging will be different at run time”. The Content Hugging label in shown in two lines.

If you need any assistance in Auto Layout, check out our new iOS 9 Auto Layout Tutorials 50% Off.

Filed Under: Auto Layout, Xcode Tagged With: Compression Resistance, Content Hugging

Primary Sidebar

Recent Posts

  • We have blocked all requests from this device – Firebase Phone Authentication
  • iPhone is not available error message in Xcode
  • Clear CocoaPods cache, re-download and reinstall all pods
  • PDFKit – View, Annotate PDF file in Swift
  • Tab Bar Controller with WebView

Archives

  • September 2020
  • April 2020
  • December 2019
  • November 2019
  • October 2019
  • February 2019
  • October 2017
  • June 2017
  • May 2017
  • March 2017
  • September 2016
  • March 2016
  • February 2016
  • January 2016
  • December 2015
  • November 2015
  • October 2015
  • September 2015
  • August 2015
  • July 2015
  • June 2015
  • May 2015
  • April 2015
  • March 2015
  • February 2015
  • January 2015
  • December 2014
  • November 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • April 2014
  • March 2014
  • February 2014
  • January 2014
  • December 2013
  • October 2013
  • August 2013
  • July 2013
  • June 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • November 2012
  • August 2012
  • July 2012
  • June 2012
  • May 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • April 2011
  • March 2011
  • January 2011
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • July 2009
  • March 2008

Copyright 2020 © rshankar.com