How to detect shakes in an iPhone Application?

This post deals with detecting shakes in an iPhone application. The shake API has 3 events which can be handled in your code

a) motionBegan:

b) motionEnded:

c) motionCancelled:

Now lets see how you can code these events in your application

1)Open Xcode, make a view based application and name it as shake.

2)Open shakeViewController.xib and populate it with a TextField and a UIDatePicker as shown below

3) Now open shakeViewController.h file. Add the following highlighted code

 

#import <UIKit/UIKit.h>
@interface ShakeViewController : UIViewController {
IBOutlet UITextField *textField;
IBOutlet UIDatePicker *datePicker;
}
@property (nonatomic, retain) UITextField *textField;
 @property (nonatomic, retain) UIDatePicker *datePicker;
-(IBAction) doneEditing: (id) sender;
@end

 

4) In the Interface Builder make the connections for textField and datePicker

5) Right click the textField and connect its Did End On Exit event to doneEditing: method as shown below

 

 

6) Now write the following highlighted code in the shakeViewController.m file

 

#import "ShakeViewController.h"
@implementation ShakeViewController
@synthesize textField, datePicker;
-(void) viewDidAppear:(BOOL)animated
{
[self.view becomeFirstResponder];
 [super viewDidAppear:animated];
}
-(IBAction) doneEditing: (id) sender
{
 [self.view becomeFirstResponder];
}
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.subtype == UIEventSubtypeMotionShake )
 {
NSLog(@"motionBegan:");
}
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
 if (event.subtype == UIEventSubtypeMotionShake )
{
NSLog(@"motionCancelled:");
}
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
 {
 if (event.subtype == UIEventSubtypeMotionShake )
{
NSLog(@"motionEnded:");
}
}
-(void)dealloc
{
[textField release];
 [datePicker release];
[super dealloc];
}

 

7) Right click the classes group and choose add new file. Select the UIView subclass template.

 

8) Name the file as ShakeView.

9) Open ShakeView.m and add the following method

-(BOOL)canBecomeFirstResponder
{
 return YES;
}

 

10) In Interface Builder, select the View window and view its Identity Inspector window. Select its class name as ShakeView.

 

11) Save everything and then run the application.

12) To simulate shaking on simulator choose Hardware->Shake Gesture

13) Observe the console.

Note: You should have first responder in your view to fire the events. So we have set view to first responder in viewDidAppear: and then again when keyboard is dismissed we make view as first responder in doneEditing: method. By default your view will never be first responder so you will have to override the default canBecomeFirstResponder method to return a YES:

 

How to animate switching of views?

This snippet deals with animating switching of views.

 

Normally when users have to switch views they simply add the following code

[self.view addSubview:someview];

and to remove this view from superview they use

[self.view removeFromSuperview];

The above code do not perform any animations while switching views. They simply switch.

Adding few lines of code can make switching of views more interesting.

While you add or remove views just do it inside following code to add life to the switching of views.

 

[UIView beginAnimations:@"flipping view" context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
[self.view addSubview:someViewController.view];
[UIView commitAnimations];

Now lets see what these lines of code do.

1) begin Animations: start our animation block. You can give any name in place of @”flipping view”.

2) setAnimationDuration: sets the duration for which the animation will last.

3) setAnimationCurve: sets the curve of animating property changes with in an animation. You can use following constants in this place

➤    UIViewAnimationCurveEaseInOut —cause the animation to begin slowly, accelerate through the middle of its duration, and then slow again before completing.

➤    UIViewAnimationCurveEaseIn — causes the animation to begin slowly and then speed up as it progresses

➤    UIViewAnimationCurveEaseOut — causes the animation to begin quickly and then slow as it completes

➤    UIViewAnimationCurveLinear — causes an animation to occur evenly over its duration

4) setAnimationTransition: applies a transition type to the animation. Following constants can be used.

➤ UIViewAnimationTransitionNone — no transition

➤ UIViewAnimationTransitionFlipFromLeft — flips a view around vertical axis from left to right

➤ UIViewAnimationTransitionFlipFromRight — flips a view around a vertical axis from right to left

➤ UIViewAnimationTransitionCurlUp — curls a view up from the bottom

➤UIViewAnimationTransitionCurlDown — curls a view down from the top

5) addSubView: is the usual method by which you add a subview to a view. Here someViewController is a class object whose view we want to add.

6) In the end we commit our animation block.

How to implement searching in UITableView

How to implement searching in UITableView

 

So, today we are going to see how to  implement Searching of data in UITableView.
Given below is the snapshot of what will our app look like.

iPhone Application Development

So lets get started :-


1.) Creating a new project

The first step is to create a new project. For this we need to :-

a.) launch Xcode.
b.) click on File -> New Project.
c.) select Application (under iOS).
d.) select View-Based Application project template.
e.) Under Product , choose iPad.
f.) click on choose.
g.) save the project and  name it “search”.

iPhone Application Development

This is how the list of files look like in Xcode.

iPhone Application Development

2.)Building the Interface


Go to “Resources” folder and click “searchViewController.xib” file. This will launch the “Interface Builder” which consists of few windows.

a.)Now we will go to the “Library window” and from there we will select the “Search Bar” and “Table View” drag it to the “View window”.
b.) We will make the interface as shown in the figure and name the objects according to it.

iPhone Application Development

3.)Writing Code

a.)So Code for “searchViewController.h” file


There would be a piece of code that Xcode has already written for you. Here’s what the whole code will look like.

#import <UIKit/UIKit.h>

@interface searchViewController : UIViewController
<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>{
	NSMutableArray *listOfItems;
	UITableView *tableView;
	IBOutlet UISearchBar *sBar;
	NSMutableArray *copyListOfItems;
	BOOL searching;

}
@property(nonatomic,retain)UITableView *tableView;
-(void) searchTableView;
- (void) doneSearching_Clicked:(id)sender;

@end

Here  we have  the delegates for the UUISearchBar, TableView and TableViewDataSource.

We  also declare a TableView object, a SearchBar object and few other objects which needs will be explained in the next step.

We declare two methods “searchTableView” and “doneSearching_Clicked” which will be called for searching and end searching respectively.

 

b.)Code for “searchViewController.m” file

 

In this part we synthesize the “tableView” object and in “viewDidLoad” method we allocate the objects to the “MutuableArray”.

We implement the methods “searchBarDidBeginEditing” and “doneSearching_Clicked”.

Here we allocate the number of sections and number of rows in the TableView.

In “searchTableView” object we implement the logic for search.

We define a temporary string that contains the string entered in the “SearchBar”.

Then  this  string is matched with the objects of the array in the “TableView” and the results are  stored in another array “copyListOfItems” and is displayed.

4.)Building the Connections

#import "searchViewController.h"

@implementation searchViewController
@synthesize tableView;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Countries";
	listOfItems = [[NSMutableArray alloc] initWithObjects:@"Iceland", @"Greenland", @"Switzerland", @"Norway",@"Sri Lanka",@"China", @"New Zealand", @"Greece", @"Rome", @"Ireland",@"India", @"U.S.A", nil];

	//Initialize the copy array.
	copyListOfItems = [[NSMutableArray alloc] init];

	//Set the title
	self.navigationItem.title = @"Countries";
    searching = NO;
	sBar.autocorrectionType = UITextAutocorrectionTypeNo;
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {

	searching = YES;
	self.tableView.scrollEnabled = NO;

		}

- (void) doneSearching_Clicked:(id)sender {

	[sBar resignFirstResponder];

	self.navigationItem.rightBarButtonItem = nil;
	self.tableView.scrollEnabled = YES;

}

- (NSIndexPath *)tableView : (UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	return indexPath;

}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

	//Remove all objects first.
	[copyListOfItems removeAllObjects];

	if([searchText length] > 0) {

		[self searchTableView];

	}
	else{
		searching=NO;

	}
	[self.tableView reloadData];

}

- (void) searchTableView {

	searching = YES;
	NSString *searchText = sBar.text;
	NSMutableArray *searchArray = [[NSMutableArray alloc] init];

	[searchArray addObjectsFromArray:listOfItems];

	for (NSString *sTemp in searchArray)
	{
		NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

		if (titleResultsRange.length > 0)
			[copyListOfItems addObject:sTemp];
	}

	[searchArray release];
	searchArray = nil;
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

	return 1;

}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

	if (searching)
		return [copyListOfItems count];
	else {
		return [listOfItems count];
	}
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	static NSString *CellIdentifier = @"Cell";

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	}

	// Set up the cell...

	if(searching)
		cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
		else {

			//First get the dictionary object

			cell.textLabel.text = [listOfItems objectAtIndex:indexPath.row];
		}

	return cell;
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)dealloc {
	[sBar release];
	[tableView release];
	[listOfItems release];
    [super dealloc];
}

@end

Our next step is to build the connections between the code we have written with our Interface elements.

a.)So we click on the “searchViewController.xib” in the “Resources” folder to launch “Interface Builder.

b.)There in the “Document window” we select “File’s Owner” and right click it.

c.)Now a window pops up which shows all the “Outlets and Actions” defined by us.

d.)Do the connections as shown below.

iPhone Application Development

5.)Build and Run

iPhone Application Development
Now finally we have to go to the Xcode and there at the top bar we see “Build and Run”. Just click it to run the application. Make sure we have saved our application before doing this.

So finally our app will look something like this:-

iPhone Application Development

 

How to detect touches in iPhone/iPad application programming?

This post deals with detecting multi-touches on iPhone screen.

One of the most important feature of iPhone is its touchscreen which can detect multiple touches. This feature allows most natural interaction with objects visible on iPhone screen.

Lets start

1) Create a new view based application and name it Multi-Touch.
2)Drag and drop an image into resource folder. Lets say the name of image is apple.jpeg.

 

3) Open MultiTouchViewController.xib file

4) Populate the view with ImageView. Ensure that ImageView covers the entire view.

5) Select image property on the ImageView to apple.jpeg in its Attribute window.

6) Open MultiTouchViewController.h and write the following highlighted code

 

7) Drag the File’s Owner item to the ImageView view. Select imageView.

8) Write the following code in MultiTouchViewController.m

 

@synthesize imageView;
//---fired when the user finger(s) touches the screen---
-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
//---get all touches on the screen---
 NSSet *allTouches = [event allTouches];
//---compare the number of touches on the screen
switch ([allTouches count]) {
//---single touch---
case 1: {
//---get info of the touch---
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
//---compare the touches---
switch ([touch tapCount]) {
//---single tap---
case 1: {
imageView.contentMode = UIViewContentModeScaleAspectFit;
}
 break;
//---double tap---
case 2: {
imageView.contentMode = UIViewContentModeCenter;
}
break;
}
}
break;
}
}

 

As we see above that we use “touchesBegan:” delegation method which is fired when user touches the screen. NSSet object allTouches tells that how many fingers are touching the screen. We extract details of the first touch by using the allObjects method of the NSSet object to return an NSArray object. The UITouch object (touch) contains the tapCount property, which tells us whether the user has single-tapped the screen or performed a double tap (or more).

9) Save and Build the application.

10) Single tap the image to enlarge it and double tap to return to its original size.

 

How to sort data and display in UITableView

How to sort data and display in UITableView

 

So,  today we are going to see how to make a simple app in iPad that will sort the list of countries in ascending or in descending order as per required.

Given below is the snapshot of what will our app look like.

iPhone Application Development

 

So lets get started :-

1.) Creating a new project


The first step is to create a new project. For this we need to :-

a.) launch Xcode.
b.) click on File -> New Project.
c.) select Application (under iOS).
d.) select View-Based Application project template.
e.) Under Product , choose iPad.
f.) click on choose.
g.) save the project and  name it “sort”.

iPhone Application Development

This is how the list of files look like in Xcode.

iPhone Application Development

2.)Building the Interface


Go to “Resources” folder and click “sortViewController.xib” file. This will launch the”Interface Builder” which consists of few windows.

a.)Now we will go to the “Library window” and from there we will select the “Table View” and drag it to the “View window”.

b.)Same way we are going to drag  ”Segmented Control”.

c.) We will make the interface as shown in the figure and name the objects according to it.

iPhone Application Development

3.)Writing Code


a.)So Code for “sortViewController.h” fil


There would be a piece of code that Xcode has already written for you. Here’s what the whole code will look like.

#import <UIKit/UIKit.h>

@interface sortViewController : UIViewController <UITableViewDataSource>{
	NSMutableArray *sortedArray;
	IBOutlet UITableView *tableView;
	IBOutlet UISegmentedControl *segmentedControl;
}
@property(nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;
@property(nonatomic,retain) IBOutlet UITableView *tableView;
-(IBAction) do_sorting;

@end

Here we declare an Mutable Array that will contain the sorted list of countries , a Table View object and Segmented Control objects.

We set the property for the  SegmentedControl and the TableView Object.
A function “do_sorting” which when called will sort the list in acending or descending as required.

Property List:

Property lists organize data into named values and lists of values using several object types. These types give you the means to produce data that is meaningfully structured, transportable, storable, and accessible, but still as efficient as possible.

We will use them here to organize the list of countries we will be sorting out.

Lets see how to create a Property List also known as plist.

a.) In Xcode, go to File.
b.) click on File -> New File.
c.) select Resources (under Mac OS X).
d.) select Property List file template.
e.) click on choose.
f.) save and  name it as “country”.

iPhone Application Development

Fill it with the name of some countries and save it in the “Resources” directory.

The plist will look something like this,

iPhone Application Development

b.)Code for “sortViewController.m” file


#import "sortViewController.h"

@implementation sortViewController
@synthesize segmentedControl;
@synthesize tableView;
-(IBAction) do_sorting{

	if (segmentedControl.selectedSegmentIndex == 1) {

		NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
		[sortedArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
		[tableView reloadData];
	}
	else {

		NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
		[sortedArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
		[tableView reloadData];
	}

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

	return @"Country";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return [sortedArray count];

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

	UITableViewCell *cell = [[UITableViewCell alloc]
							 initWithStyle:UITableViewCellStyleDefault
							 reuseIdentifier:@"cell"];

	cell.textLabel.text = [sortedArray objectAtIndex:indexPath.row];

	return cell;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

	NSString *myfile = [[NSBundle mainBundle]
						pathForResource:@"country" ofType:@"plist"];
	sortedArray = [[NSMutableArray alloc]initWithContentsOfFile:myfile];

    NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
	[sortedArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
    [super viewDidLoad];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@end

We synthesize the “SegmentedControl” and “TableView” object .

In the “numberOfSectionsInTableView” method we return 1 as we are having only 1 section in the Table and we set the Title for the table as “Country”.

In “viewDidLoad” method, we bundle the plist with the Array object “­­­­­­­­­sortedArray”. We then declare an object of  “NSSortDescriptor” class that is a built in class which is used for sorting.

When app is loaded, table is filled with the elements of the array “sortedArray”.

“do_sorting” method sorts the list in ascending or descending order as required by using “NSSortDescriptor” class.

 

4.)Building the Connections


Our next step is to build the connections between the code we have written with our Interface elements.

a.)So we click on the “sortViewController.xib” in the “Resources” folder to launch “Interface Builder.

b.)There in the “Document window” we select “File’s Owner” and right click it.

c.)Now a window pops up which shows all the “Outlets and Actions” defined by us.

d.)Do the connections as shown below.

iPhone Application Development

 

5.)Build and Run


Now finally we have to go to the Xcode and there at the top bar we see “Build and Run”. Just click it to run the application. Make sure we have saved our application before doing this.

iPhone Application Development

So finally our app will look something like this:-

iPhone Application Development

How to use UIPopoverController in iPad programming?

This post deals with using UIPopoverController in iPad programming..

 

UIPopoverController is an iPad specific controller. UIPopoverController is not actually a ViewController in itself but it manages the presentation of view controllers. Popovers provide a lightweight way to present or gather information from the user and are commonly used in the following situations:

 

  • To display information about an object on the screen.
  • To manage frequently accessed tools or configuration options
  • To present a list of actions to perform on objects inside one of your views
  • To present one pane from a split view controller when the device is in a portrait orientation

Now we will see how we can make a UIPopoverController as shown above

We will take two view controllers for this tutorial

The first view controller will be popoverViewController and second view controller will be popViewController

The left pane of Xcode will look something like this

Now first come to popViewController.h and write the following code as highlighted

 

 

“delegate” property  will be assigned the object of popoverViewController class. So popoverViewController object will have the implementation of “-(void) dismiss:(popViewController *) controller;”. This method will be used to dismiss UIPopoverController. Also this is the view controller class which will be presented as a popover on the press of a button.

 

Open popViewController .xib, drag a table view on it as shown below and make the UITableViewDataSource and UITableViewDelegate connections

 

 

The above popViewController’s view will be shown as a popover and will change the value of the label in popoverViewController’s view on the selection of a row.

 

Now come to popViewController.m file

 

Populate the array with three values in viewDidLoad method

 

array=[[NSArray alloc] initWithObjects:@"JOHN",@"MIAMI",@"DEAN",nil];

Now write the following delegation methods of table view

 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

	return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}

	cell.textLabel.text=[array objectAtIndex:(indexPath.row)];
	return cell;
	}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	popoverViewController *p=(popoverViewController *)self.delegate;
	UILabel *label;
	label=p.label;

	label.text=[array objectAtIndex:indexPath.row];
	[self.delegate dismiss:self];
	NSLog(@"hello");

}

 

As we can see from the above code that the popover, which contains the content of popViewController class, will be containing three rows. Property delegate references popoverViewController object because it acts as the delegate for popViewController and implements “-(void) dismiss:(popViewController *) controller;” method as said above. This method will contain the code to dismiss the popover. So on selection of row, the value of the label in popoverViewController will be changed to the row’s value and popover will be dismissed.

 

Now come to popoverViewController.h file and write the following highlighted code

 

As this class acts as the delegate for popViewController class, so it implements popViewControllerDelegate. UIPopoverController’s object popover will be used to represent the content of popViewController class in popover style A label will be attached in popoverViewController.xib file which will change value on selection of row in popover.”pop:” method will be fired when bar button will be pressed and will show the popover.

 

Now come to popoverViewController.xib. Drag label and barbutton, and make connections as shown

 

 

Now open popoverViewController .m file

 

Implements the pop: method as shown below

 

-(IBAction)pop:(id)sender
{
	popViewController *pop=[[popViewController alloc] initWithNibName:@"popViewController" bundle:nil];
	pop.delegate=self;

	UIPopoverController* aPopover = [[UIPopoverController alloc]initWithContentViewController:pop];

	[pop release];
	self.popover = aPopover;

	self.popover.popoverContentSize=CGSizeMake(300, 500);
    [aPopover release];
	[self.popover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

 

In the above code we made a popViewController object which will be presented in a popover style with the help of UIPopoverController object. We set the “self” object as the delegate for popViewController object. After this we set the popover size by using property “popoverContentSize”. At last we display the popover.

Implement the delegate method “-(void) dismiss:(popViewController *) controller;”

 

-(void) dismiss:(popViewController *) controller
{
	[self.popover dismissPopoverAnimated:YES];
}

The above method will dismiss the popover

Save and build the application. Output is as shown below

 

Just click some row and you will see the value of label changing

How to use UIScrollView for the contents that are larger than iPhone screen?

This post deals with using UIScrollView for the contents which are larger than iPhone Screen.

 

Scroll views have two main purposes

1)To let users drag the area of the content they want to display.

2)To let users zoom into or out of the displayed content using pinch gestures.

We are going to see both of the above functionalities in this tutorial.

Lets say we have an image waterfall-wallpaper.jpg, with a size of 1024×768, which is bigger than iPhone screen and we want to display it on screen such that every potion of image can be seen by dragging.

 

Open .xib file

Drag a UIScrollView and arrange it as shown in figure. You may add a navigation bar also. In this tutorial navigation bar is added.

 

 

 

Now come to .h file and write the following highlighted lines of code

 

Now move to .m file and write the following code in viewDidLoad method

tempScrollView.minimumZoomScale=0.5;

    tempScrollView.maximumZoomScale=6.0;
	tempScrollView.delegate=self;
    tempScrollView.contentSize=CGSizeMake(1024,768);
	UIImage *image=[UIImage imageNamed:@"waterfall-wallpaper.jpg"];
	imview=[[UIImageView alloc] initWithImage:image];
	[tempScrollView addSubview:imview];

Here maximumZoomScale and minimumZoomScale are maximum and minimun amount of zooming a user can do.

contentSize is the size of the content to be scrolled. In this exanple image size is 1024×768

 

Also add the following delegate method for pinch gestures

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView

{

    return imview;

}

Now it’s time to connect tempScrollView outlet to UIScrollView in .xib file

Connect as shown in figure.

Save and Build the application.

Now try to move the image and you will be able to see any portion of the image.

Pinching in causes the image to zoom in and pinching out causes the image to zoom out.

For those of you testing on simulator, pinching can be performed by holding the “option”  key and moving the finger on trackpad.

How to find date and time programmatically in different formats?

This post deals with finding out date and time programmatically in different formats.

Open .xib file

Drag 6 labels and arrange them as shown in figure

Name of the labels are

1)Date

2)label2

3)Time

4)label2

5]Date and Time with time zone

6)label3

Now come to .h file

Write the following highlighted lines of code

Now move to .m file

synthesize these labels

@synthesize label1,label2,label3;

Now in viewDidLoad function write the following code

NSDate *now = [[NSDate alloc] init];

	NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"yyyy-MM-dd"];
	NSString *date=[df stringFromDate:now];
	label1.text=date;
	 df = [[NSDateFormatter alloc] init];

	[df setDateFormat:@"hh:mm:ss a"];
	date=[df stringFromDate:now];
	label2.text=date;
	[df setDateFormat:@"yyyy-MM-dd hh:mm:ss a zzz"];
	date=[df stringFromDate:now];
	label3.text=date;

In the above code we can see that three different formats for date and time have been set. You can try your own format also for example “yyyy” will give only year.

Now  open Interface Builder and make connections as shown in figure

 

Save and build the application. You will get output like shown below

 

How to use UISegmentedControl in iPhone & iPad

UISegmentedControl in iPhone & iPad

 

So today we are going to create a simple app that is going to use UISegmentedControl . In our previous tutorials we created simple iPhone app. This time we are going to create an iPad application. The process and code is exactly same for both of these, we just need to initially select it in the Xcode.

 

Basically our app will have a menu with name of some colors written on each menu. Whenever a menu is selected, the color of the text is changed to that represented by the menu.

Given below is the snapshot of what will our app look like.

iPhone Application Development

 

So lets get started :-

1.) Creating a new project

The first step is to create a new project. For this we need to :-

a.) launch Xcode.
b.) click on File -> New Project.
c.) select Application (under iOS).
d.) select View-Based Application project template.
e.) Under Product , choose iPad.
f.) click on choose.
g.) save the project and  name it “menu”.

 

iPhone Application Tutorial

This is how the list of files look like in Xcode.

iphone Application Development

 

2.)Building the Interface

Go to “Resources” folder and click “menuViewController.xib” file. This will launch the “Interface Builder” which consists of few windows.

a.)Now we will go to the “Library window” and from there we will select the “Text View” and drag it to the “View window”.

b.)Same way we are going to drag  ”Segmented Control” .

c.) We will make the interface as shown in the figure and name the objects according to it.

iPhone Application Development

 

3.)Writing Code

a.)So Code for “menuViewController.h” file

There would be a piece of code that Xcode has already written for you. Here’s what the whole code will look like.

#import <UIKit/UIKit.h>

@interface menuViewController : UIViewController {
	IBOutlet UISegmentedControl *mycolors;
	IBOutlet UITextView *sampleText;

}

@property(nonatomic,retain) IBOutlet UISegmentedControl *mycolors;
@property(nonatomic,retain) IBOutlet UITextView *sampleText;

-(IBAction) colorChanged;

@end

Here we declare a  “SegmentedControl” object and a “TextView” object and set their property.

We declare a function “colorChanged” which when called will change the color of the “TextView.”

 

b.)Code for “menuViewController.m” file:

#import "menuViewController.h"

@implementation menuViewController

@synthesize mycolors,sampleText;

-(IBAction) colorChanged {

if (mycolors.selectedSegmentIndex==0)
{
sampleText.textColor = [UIColor blackColor];
}
if (mycolors.selectedSegmentIndex==1)
{
sampleText.textColor = [UIColor greenColor];
}
if (mycolors.selectedSegmentIndex==2)
{
sampleText.textColor = [UIColor blueColor];
}
if (mycolors.selectedSegmentIndex==3)
{
sampleText.textColor = [UIColor brownColor];
}
if (mycolors.selectedSegmentIndex==4)
{
sampleText.textColor = [UIColor redColor];
}
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc {
[mycolors release];
[sampleText release];
[super dealloc];
}

@end

Here we synthesize the “mycolors” and “sampleText” objects.

Now we define the “colorChanged” method. It checks for the index value of the  “SegmentedControl” and changes the color of  “sampleText” according to it.

 

4.)Building the Connections

Our next step is to build the connections between the code we have written with our Interface elements.

a.)So we click on the “menuViewController.xib” in the “Resources” folder to launch “Interface Builder.

b.)There in the “Document window” we select “File’s Owner” and right click it.

c.)Now a window pops up which shows all the “Outlets and Actions” defined by us.

d.)Do the connections as shown below.

iPhone Application Development

 

5.)Build and Run

Now finally we have to go to the Xcode and there at the top bar we see “Build and Run”. Just click it to run the application. Make sure we have saved our application before doing this.

iPhone Application Development

So finally our app will look something like this:-

iPhone Application Development


How to display a custom view instead of standard keyboard when the textfield becomes first responder?

This snippet deals with how to display custom view instead of keyboard when the textfield becomes first responder…

 

Write the highlighted code, as shown below, in .h file

Now come to .m file and write the code give below

@synthesize field;

Inside viewDidLoad method write the following code

UIImage *image=[UIImage imageNamed:@"apple-logo.jpg"];
	UIImageView *view=[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100, 200.0f)];
	[view setImage:image];

	field.inputView=view;

Here apple-logo.jpg is the image in the resource folder

 

Now come to .xib

Add a textfield and a label as shown below. Also make the connection

Now when you interact with textfield you will get your own view instead of keyboard