• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Ravi Shankar

How to programmatically add AutoLayout constraints?

February 18, 2016 By Ravi Shankar 2 Comments

AutoLayout solves the mystery when designing app for more than one screen size and for both Portrait and Landscape orientation. This is done by adding constraints to the views using various Auto Layout options available as part of Interface Builder. As an iOS developer, you can also add these constraints programmatically using NSLayoutConstraints or Visual Format Languages. In this tutorial we will see how to use NSLayoutConstraints for adding constraints to the views.

Screen Design For this Demo

For this demo, we will design something similar to flag of England by adding all the views and constraints programmatically. Funza Academy have published a video tutorial on how to design this screen using Interface Buidler, please check that out.

 

Overview of Steps

The following will be done to create the UI programmatically.

  1. Change the background colour of View to Red
  2. Add four rectangular views of equal widths on top left, top right, bottom left and bottom right of the parent view. The background colour for all these views will be set to red and Super View to red
  3. Pin the four rectangular views to the corresponding corner by adding constraints.
  4. Add constraints to the views to leave constant gap between each views (white background). This would ensure red line is shown in between these views.
  5. Disable AutoResizingMasks for teh four sub views.

Project Setup

Create a new Xcode project by selecting Single View Application for the project template. Also choose the language and Swift and iPhone for Devices.

Create Views

Navigate to ViewController.swift file and add the following code snippet after the class declaration and above the viewDidLoad() function.

[code language=”swift”]private let SCREEN_SIZE = UIScreen.mainScreen().bounds
private let GAP_BETWEEN_VIEWS:CGFloat = 0.08

// Create four Subviews

var topLeftView = UIView()
var topRightView = UIView()
var bottomLeftView = UIView()
var bottomRightView = UIView()[/code]

The above set of code creates two constants which stores the screen size and specifies the gap between the views. Then we have created four variables that holds the instance of four views.

Add the following addViews functions below the viewDidLoad method

[code language=”swift”]
func addViews() {
let heightOfSubView = SCREEN_SIZE.height / 2 – SCREEN_SIZE.height * GAP_BETWEEN_VIEWS/2
let widthOfSubView = SCREEN_SIZE.width / 2 – SCREEN_SIZE.height * GAP_BETWEEN_VIEWS/2

// Calculate the height and size of each views
topLeftView = UIView(frame: CGRect(x: 0, y: 0, width: widthOfSubView, height: heightOfSubView))
topRightView = UIView(frame: CGRect(x: widthOfSubView + (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS), y: 0, width: widthOfSubView, height: heightOfSubView))
bottomLeftView = UIView(frame: CGRect(x: 0, y: heightOfSubView + (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS), width: widthOfSubView, height: heightOfSubView))
bottomRightView = UIView(frame: CGRect(x: widthOfSubView + (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS), y: heightOfSubView + (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS), width: widthOfSubView, height: heightOfSubView))

topLeftView.backgroundColor = UIColor.whiteColor()
topRightView.backgroundColor = UIColor.whiteColor()
bottomLeftView.backgroundColor = UIColor.whiteColor()
bottomRightView.backgroundColor = UIColor.whiteColor()

view.addSubview(topLeftView)
view.addSubview(topRightView)
view.addSubview(bottomLeftView)
view.addSubview(bottomRightView)
}
[/code]

The addViews function, calculates the height and width of each subview (rectangular view with white background). Then the four views are created with positioning them in the corresponding corners i.e topLeft, topRight, bottomLeft and bottomRight. The background colour for these views are set White then they added to parent view using addSubView method.

Now call this addViews function inside viewDidLoad method. Also make sure to set the background colour of parent view to red.

[code language=”swift”]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.redColor()
addViews()
}
[/code]

Compiling and running this app on iPhone 6 simulator, the portrait mode should look as shown below

And in Landscape mode the views are randomly placed. Let us now fix this by adding the required constraints for all the veiws.

Add Constraints

In order to pin the four subviews, we need to add Leading, Traling, Top and Bottom constraints for the views based on their position. For example the top left view needs a leading and top constraint to the superview. The below screenshot should give a better understanding of constraints required for each view. And we will be adding these constraints using NSLayoutConstraint class

Pin the views to the side

Add the following code snippet that which creates Leading and Top constraint for TopLeft view.

[code language=”swift”]func addtopLeftViewConstraints() {
let topLeftViewLeadingConstraint = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)

let topLeftViewTopConstraint = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)

NSLayoutConstraint.activateConstraints([topLeftViewLeadingConstraint, topLeftViewTopConstraint])
}
[/code]

First we create a leading constraint to the topLeft view and super view. Then a top constraint is added for topLeft view to the SuperView. Constant refers to the gap between the views using attribute we specify the Leading or Top attributes. Since we do not need any gap between corners the constant value is set to 0. Finally we add these constraints for the view by using the activateConstraints function in NSLayoutConstraint class.

Now let us repeat the above steps topRight. bottomLeft and bottomLeft Views.

[code language=”swift”]func addTopRightViewConstraints() {

let topRightViewTrailingConstraint = NSLayoutConstraint(item: topRightView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)

let topRightViewTopConstraint = NSLayoutConstraint(item: topRightView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)

NSLayoutConstraint.activateConstraints([topRightViewTrailingConstraint, topRightViewTopConstraint])
}

func addBottomLeftViewConstraints() {

let bottomLeftViewLeadingConstraint = NSLayoutConstraint(item: bottomLeftView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)

let bottomLeftViewBottomConstraint = NSLayoutConstraint(item: bottomLeftView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)

NSLayoutConstraint.activateConstraints([bottomLeftViewLeadingConstraint, bottomLeftViewBottomConstraint])

}

func addBottomRightViewConstraints() {

let bottomRightViewTrailingConstraint = NSLayoutConstraint(item: bottomRightView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)

let bottomRightViewBottomConstraint = NSLayoutConstraint(item: bottomRightView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal
, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)

NSLayoutConstraint.activateConstraints([bottomRightViewTrailingConstraint, bottomRightViewBottomConstraint])
}[/code]

Leave space between views

We need leave constant space in the middle between these views. This can be achieved by adding constriants between the top/bottom views and left/right views. So basically we need to add two vertical spacing and two horizontal spacing constraints.

The below code snippet adds the required spacing constraings between views by specifying a constant value. Then activate these constraints by calling NSLayoutConstraint.activateConstraint.

[code language=”swift”] func addTopBottomConstraints() {
let verticalSpacing1 = NSLayoutConstraint(item: bottomLeftView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: topLeftView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS))

let verticalSpacing2 = NSLayoutConstraint(item: bottomRightView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: topRightView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS))

NSLayoutConstraint.activateConstraints([verticalSpacing1, verticalSpacing2])
}

func addLeftRightConstraints() {
let horizontalSpacing1 = NSLayoutConstraint(item: topRightView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: topLeftView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS))

let horizontalSpacing2 = NSLayoutConstraint(item: bottomRightView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: bottomLeftView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: (SCREEN_SIZE.height * GAP_BETWEEN_VIEWS))

NSLayoutConstraint.activateConstraints([horizontalSpacing1, horizontalSpacing2])
}
[/code]

Add Equal Width and Equal Height

Now add Equal Width and Equal Height constraints for topRight, bottomLeft and bottomRight views based on topLeft View. The code snippet for EqualWidth and EqualHeight is given below. The first function adds equal width constaints for all the three views based on TopLeft view. Similarly the second function adds equal height constraints based on the TopLeft view.

[code language=”swift”]
func addEqualWidthConstraints() {
let topRightViewWidth = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: topRightView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)

let bottomLeftViewWidth = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: bottomLeftView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)

let bottomRightViewWidth = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: bottomRightView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)

NSLayoutConstraint.activateConstraints([topRightViewWidth, bottomLeftViewWidth,bottomRightViewWidth ])
}

func addEqualHeightConstraints() {
let topRightViewHeight = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: topRightView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)

let bottomLeftViewHeight = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: bottomLeftView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)

let bottomRightViewHeight = NSLayoutConstraint(item: topLeftView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: bottomRightView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)

NSLayoutConstraint.activateConstraints([topRightViewHeight, bottomLeftViewHeight,bottomRightViewHeight ])
}[/code]

Disable AutoResizingMasks

Finally we need to disable the auto resizing masks for all the views to prevent constraints getting automatically based on the autoResizingMask property. The autoResizingMask property is set to true when the views are added programmtically added so we need make sure that this property for all these views are set to false.

[code language=”swift”]func disableAutoResizingMasks() {
topLeftView.translatesAutoresizingMaskIntoConstraints = false
topRightView.translatesAutoresizingMaskIntoConstraints = false
bottomLeftView.translatesAutoresizingMaskIntoConstraints = false
bottomRightView.translatesAutoresizingMaskIntoConstraints = false
}[/code]

Just to make code little organized, we can create a new function that calls these constraints functions.

[code language=”swift”]func addConstraints() {
addtopLeftViewConstraints()
addTopRightViewConstraints()
addBottomLeftViewConstraints()
addBottomRightViewConstraints()
addTopBottomConstraints()
addLeftRightConstraints()
addEqualWidthConstraints()
addEqualHeightConstraints()
disableAutoResizingMasks()
}
[/code]

Then call the addConstraints function in viewDidLoad method

[code language=”swift”]override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = UIColor.redColor()

addViews()
addConstraints()
}[/code]

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

Download the source code from GitHub

Filed Under: Auto Layout, ios Tagged With: NSLayoutConstraint, Swift

A trick to flip a column upside down in Excel

February 17, 2016 By Ravi Shankar Leave a Comment

Excel users can sort a column using the Sort feature available as part of Sort & Filter menu. But what if you want to flip a column upside down. Let us see this with an example column having some text values as shown below.

We will not be able to apply sort feature directly on this column to flip the data instead we can add a dummy column and use that for sorting the text values.

Step 1: Insert a new column before the existing column.
Step 2: Now use Auto Fill feature to fill the temp with numbers as shown below

Step 3: Now you can use the Sort feature on column1 and make sure to sort by descending order. Also include the column2 in Sort sleection list.

Step 4: Once the columns are sorted, delete the temp column with numbers.

Filed Under: Excel, Excel 2007, Excel 2010, Excel 2013, MS Office

Prevent users from adding new worksheet in Excel

January 25, 2016 By Ravi Shankar 2 Comments

Excel 2016, 2013 and 2010 provides an option to prevent users from adding new worksheet to existing Workbook structure. So if you are the owner of Excel file and you do not want to allow other users to add any new worksheet, rename or move worksheet then you can use Protect Workbook Structure option to change the permission. You can access Protect Workbook Structure from the Info menu.

image

Click the File menu and then navigate to Info menu and click the drop down arrow under Protect Workbook option. From the list of available option select Protect Workbook Structure. This would display the following Protect Structure and Windows. Mark the check box with label as Structure. If you want to password protect it then enter a password in the Password field. Click Ok button to save and confirm the changes.

image

Filed Under: Excel, Excel 2010, Excel 2013, Excel 2016, MS Office Tagged With: add sheet, Excel 2010, Office 2010, prevent, Protect Workbook Structure, Worksheet

Go To specific page number in Word

January 14, 2016 By Ravi Shankar 5 Comments

In Word 2013 and Word 2010 you can go to specific page in the Word document using the Find and Replace dialog.

To display the Find and Replace dialog, Navigate to Home menu and click on the drop down arrow under Find menu.

Go To option in Word 2013 and Word 2010

Another shortcut for launching Find and Replace is by pressing Ctrl + G.

Find and Replace in Word 2013 and Word 2010

Navigate Go To tab and select Page option for Go to what and specify the page number under the textbox available under Enter page number label.

Also See: Insert and Save watermark in Microsoft Word

Filed Under: MS Office, Word 2010, Word 2013 Tagged With: Go To, Office 2010, Page Number, Tips, Word 2010, Word 2013

Fix for Directory not found for option error in Xcode

January 7, 2016 By Ravi Shankar Leave a Comment

You might see Directotry not found for option error when opening an iOS 8 existing project in Xcode 7. This error because of the invalid path sepcifed from the Framework Path for the test target,

(null): Directory not found for option ‘-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator9.2.sdk/Developer/Library/Frameworks’

This can be fixed by selected the test target, navigating Search Paths and removing the entry specified for “Framework Search Paths”

Filed Under: Uncategorized Tagged With: error, Xcode

Autocorrect in Word – Replace text as you type

December 8, 2015 By Ravi Shankar Leave a Comment

Autocorrect in Microsoft Word 2016, Word 2013, 2010 and 2007 has a feature called replace any text as you type. This tutorial provides an example for replacing text with text and image in Word document.

Replace text as you type in Word 2016, Word 2013, Word 2010 and Word 2007

In Word 2013 and Word 2010 you can access Proofing section by clicking File menu –> Options. To access AutoCorrect option in Word 2007 click on the Word Options and navigate to Proofing section.

Proofing section in Word document

And on clicking the AutoCorrect Options the following dialog box would be displayed. Under Replace text as you type, you can add the text which needs to be replaced it is typed in the Word Document.

Replace text as you type in Word

For example if you want dato be replaced with Digital Answers in word document, then add da to the left hand side and Digital Answers to right hand side then click Add button.

Replace text with text using Autcorrect

How to use autocorrect for replacing text with picture

Step 1: Navigate to Insert menu, click Pictures under illustrations section

Insert Pictures in Word 2013

Step 2: Using the Insert Picture dialog, select and add image to the document.

Select Picture Dialog in Word 2013

Step 3: Click File menu, select Options from the menu list.

Word Options in Word 2013

Step 4: In Word Option window, navigate to Proofing section and click AutoCorrect Options.

AutoCorrect Options in Word 2013

Step 5: Now enter the name under Replace text and make sure Formatted Text radio option is selected. (If you have not selected any image then this option will not be displayed)

Replace text as you type in Word 2013

Step 6: Click Add button to add the entry to AutoCorrect list. Then OK button on the AutoCorrect and Word Options to close the windows.

Now whenever you type the replace text, it will be automatically replaced with the image. If you are frequently going to insert company logo or your signature then you try this feature.

Formatted Text in Word 2013

Also See: Find Autocorrect entries file in Word 2010

Filed Under: MS Office, Technical, Word 2007, Word 2010, Word 2013, Word 2016 Tagged With: AutoCorrect, Proofing, Replace text as you type, replace text with image, Word Options

How to include original message in Outlook

December 8, 2015 By Ravi Shankar Leave a Comment

Microsoft Outlook users can include the original message while forwarding or replying to an email. The users can choose any one of the following options for original message

  • Do not include original message
  • Attach original message
  • Include original message text
  • Include and indent original message text
  • Prefix each line of the original message 

Listed below are the steps to access the message handling option in Outlook 2013, Outlook 2010 and Outlook 2007

Include original message in Outlook 2016, Outlook 2013 and Outlook 2010
Click File menu, select Options from the list.

Outlook Options

In the Outlook Options window, click Mail tab then scroll down Replies and and forwards section.

Replies and forwards option in Outlook 2013, Outlook 2010

Use the option “When replying to a message” and “When forward a message” to specify the option for original message.

Include Original Message in Outlook 2013, Outlook 2010

Include original message in Outlook 2007

Tools -> Options -> Email Options -> On replies and forwards section

Email Options in Outlook 2007Attach Original message in Outlook 2007

Using the drop down available under when replying to a message and When forwarding a message, you can choose any of the following values from drop down.

Include Original message text in Outlook

Also See: Close original message on reply or forward in Microsoft Outlook

Filed Under: MS Office, Outlook 2007, Outlook 2010, Outlook 2013, Outlook 2016 Tagged With: Attach Original Message, Email Options, Include Original message, Replies and Forwards

iOS Swift – Firebase Demo

November 26, 2015 By Ravi Shankar 4 Comments

Firebase is a platform that allows web and mobile application to store data in cloud. In this article, we will see an example app written in Swift that uses Firebase for storing and retrieving data in real time. The source code for this demo is available under GitHub.

This demo app consists of three fields for capturing name, date and image. These data are then converted in to required data type for storing purpose.

Installing Firebase in iOS SDK Project

The easiest way to include Firebase SDK to your iOS project is by using Cocoapods and the instruction are clearly given in Firebase documentation section. After installing the Firebase iOS sdk make sure to create a bridge file by adding the following import statement.

[code language=”swift”]#import Firebase/Firebase.h
[/code]

Firebase DataStore

User with Google or GitHub account can directly login to Firebase. The data stored in Firebase in JSON format. Find below a screenshot of the data stored by this demo app.

Profiles is top node and under which each row is stored as key/value pairs with name as the identifier for each row. Firebase provides a path (URL ) for storing the data which ends with firebaseio.com. You should be able find this URL in Firebase main screen.

[code language=”plain”]Example :- _unique_identifier_.firebaseio.com[/code]

Saving data to Firebase

You need to create a reference to Firebase class as shown below

[code language=”swift”]let firebase = Firebase(url:”https://_unique_identifer.firebaseio.com/profiles”)[/code]

replace _unique_identifier with the identifier provided for your Firebase account.

The following piece of code is used for saving the information to Firebase.

[code language=”swift”]@IBAction func save(sender: AnyObject) {

let name = nameTextField.text
var data: NSData = NSData()

if let image = photoImageView.image {
data = UIImageJPEGRepresentation(image,0.1)!
}

let base64String = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

let user: NSDictionary = [“name”:name!,”dob”:dateOfBirthTimeInterval, “photoBase64”:base64String]

//add firebase child node
let profile = firebase.ref.childByAppendingPath(name!)

// Write data to Firebase
profile.setValue(user)
}
[/code]

The above code does the following

  1. Converts image to to JPEG also compresses the size as we will be storing the image as base64EncodedString. 
  2. Creates a dictionary with name, image (String data) and date (as timeinterval).
  3. This dictionary is then added to the FIrebase Datastore by appending the name as the identifier for each row.
  4. And to save the data to Firebase, you need to call profile.setValue by passing the dictionary object.

Retrieving data from Firebase

Here again you need to create a reference to Firebase class by passing the required path as shown below

[code language=”plain”]let firebase = Firebase(url:”https://_unique_identifer.firebaseio.com/profiles”[/code]

In the following price of code, firebase.observerEventType is used for retrieving the data from Firebase account. The data gets refreshed in real time when ever any updates happen in the data store. This is really cool!!!

[code language=”swift”]func loadDataFromFirebase() {

UIApplication.sharedApplication().networkActivityIndicatorVisible = true

firebase.observeEventType(.Value, withBlock: { snapshot in
var tempItems = [NSDictionary]()

for item in snapshot.children {
let child = item as! FDataSnapshot
let dict = child.value as! NSDictionary
tempItems.append(dict)
}

self.items = tempItems
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}[/code]

snapshot referes to the collection of records store under a path. You can iterate through the collection to reteive each data item.

Delete a row from Firebase

[code language=”swift”]override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {

let dict = items[indexPath.row]
let name = dict[“name”] as! String

// delete data from firebase

let profile = firebase.ref.childByAppendingPath(name)
profile.removeValue()
}
}
[/code]

 

Removing a row from Firebase can be done by calling removeValue method on the Firebase object reference as shown in the above code snippet.

In this tutorial, we have seen only the code related with Firebase. You can download the full source from here

Filed Under: ios, Swift Tagged With: Cloud, Firebase

  1. Pages:
  2. «
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. 7
  10. 8
  11. 9
  12. 10
  13. ...
  14. 44
  15. »
« Previous Page
Next Page »

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy