Thursday 23 June 2011

IPhone SDK : Using Table Views and Implements Their DataSource,Delegate

SelectFile > New Project or Apple Key + Shft + N to bring up the new project menu. Select the Applications item of the IPhone OS section from the menu on the left, and select View Based Application from the icons on the right. When prompted enter a project name, I have used TableView in the sample code.


There are four files in the Classes package;
TableViewTutorialAppDelegate.h
TableViewTutorialAppDelegate.m
TableViewTutorialViewController.h
TableViewTutorialViewController.m


Step 2: Create the Data Controller Class



In addition to the four files generated automatically we need to create a new class (and hence assosiated header and source files) to store the data to be displayed in the view. Select File > New File or press the the Command Key + N to open the New File Dialog. Create a new source file of type NSObject Subclass (I used the name DataController.m) and make sure you select the checkbox labeled Also create "DataController.h" file (This will be different based on the name you gave your source file).






In the DataController.h file add an instance of NSMutableArray to store actual data and also add helper methods to return size of array, item at a particular index and to add and delete items. Also add a property corresponding to the list to allow access. The complete file should look something like this:

1 #import
2 @interface DataController : NSObject
3 {
4 NSMutableArray *list;
5 }
6 - (unsigned)countOfList; //returns number of elements in list
7 - (id)objectInListAtIndex:(unsigned)theIndex; //returns object at given index
8 - (void)addData:(NSString*)data; //adds data to the list
9 - (void)removeDataAtIndex:(unsigned)theIndex;
10 @property (nonatomic, copy, readwrite) NSMutableArray *list;
11 @end

Step 2 b: Implement methods of Data Controller
First synthesize the getters and setters for the list proporty by adding @synthesize to after line 11 in DataController.m. Now implement the methods defined in the header file.

Method: countOfList
The simplest method is the list count, just call the count method on the list property and return the result.
1 - (unsigned)countOfList
2 {
3 return [list count];
4 }


Method: objectInListAtIndex
Next and just as simple is to return the element at a specific index of the list just call the objectInListAtIndex method of the list and return the result.

1 - (id)objectInListAtIndex:(unsigned)theIndex
2 {
3 return [list objectAtIndex:theIndex];
4 }


Method: removeDataAtIndex
Just add the call to the list structure.

1 - (void)removeDataAtIndex:(unsigned)theIndex
2 {
3 [list removeObjectAtIndex:theIndex];
4 }


Method: addData
I am currently using an NSString to store data but you probably want to create a domain object in a real program.

1 - (void)addData:(NSString*)data;
2 {
3 [list addObject:data];
4 }

Method: setList
We also override the set list method to make sure the mutable array remains mutable.

1 // Custom set accessor to ensure the new list is mutable
2 - (void)setList:(NSMutableArray *)newList
3 {
4 if (list != newList)
5 {
6 [list release];
7 list = [newList mutableCopy];
8 }
9 }



Method: Init and dealloc
Used to initilize the objects and free mermory respectively.

1 - (id)init
2 {
3 if (self = [super init])
4 {
5 //Instantiate list
6 NSMutableArray *localList = [[NSMutableArray alloc] init];
7 self.list = localList;
8 [localList release];
9
10 //Add initial Data
11 [self addData:@"Item 1"];
12 [self addData:@"Item 2"];
13 }
14 return self;
15 }


1 - (void)dealloc
2 {
3 [list release];
4 [super dealloc];
5 }



Step 3: Update Table View Controller

Currently the TableViewTutorialViewController inherits from the UIViewController class we need to change this to the UITableViewController. Moreover we need to add a data controller class to supply data to be displayed in the rows of the table view. For this we will add the @class declarative to our view controller header file and also create an instance of this data view class and add a property for that instance. In addition we also create a view to store the tableview and create a corresponding property. The code for TableViewTutorialViewController.h should look something like this:

1 #import

2 @class DataController;
3 @interface TableViewTutorialViewController : UITableViewController
4 {
5 DataController *dataController;
6 UIView * myView;
7 }
8
9 @property (nonatomic, retain) DataController *dataController;
10 @property (nonatomic, retain) UIView * myView;
11 @end


Step 4: Implement Table View Controller Class
The code for the of TableViewTutorialViewController.m file is shown below I will individually explain the purpose of individual lines or groups of lines . Broadly what we are doing is drawing the interface (See initWithStyle and loadView), connecting it to this controller object (See loadView line 24 and 25) and then implementing the callbacks and event handlers. (See all other mehods)

//Line 1 should already exist in the auto generated file but add line to because we are going to be using methods
//from the data controller class.
1 #import "TableViewTutorialViewController.h"
2 #import "DataController.h"

//Line 3 is auto generated but we add lines 4 nd 5 to create getters and setters for the corresponding attributes
3 @implementation TableViewTutorialViewController
4 @synthesize dataController;
5 @synthesize myView;


Method: initWithStyle
//Constructor Equivelent: used to initilize view controller (self) and data controler
6 - (id)initWithStyle:(UITableViewStyle)style
7 {
8 if (self = [super initWithStyle:style])
9 {
10 self.dataController = [[DataController alloc] init];
11 }
12
13 return self;
14 }


Method: loadView

//Define the interface and connect to controller object by specifying self as delegate and data source

15 -(void)loadView
16 {
17 // create and configure the view
18 CGRect cgRct = CGRectMake(0, 10, 320, 400); //define size and position of view
19 myView = [[UIView alloc] initWithFrame:cgRct]; //initilize the view
20 myView.autoresizesSubviews = YES; //allow it to tweak size of elements in view
21 self.view = myView; //set view property of controller to the newly created view
22 UITableView * tableView = [[UITableView alloc] initWithFrame:cgRct style:UITableViewStylePlain];
23 tableView.editing = YES; //This allows user of progrm to add or remove elements from list
24 tableView.dataSource = self;
25 tableView.delegate = self; //make the current object the event handler for view
26
27 [self.view addSubview:tableView];
28 }


Method: numberOfSectionsInTableView

//We have to implement this as the object is the data source for the table view
//Hard coded number of sections in table to 1 as we are only making a single list for this example
29 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
30 {
31 return 1;
32 }


Method: numberOfRowsInSection
//We have only one section and that section has a single datasource so we just return the number of elements in
//the datasource. We have the plus one because we want to add a speacial item at the top of the list which allows //us to add more items to the list. We see how that is done later

33 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
34 {
35 // Only one section so return the number of items in the list
36 return [dataController countOfList]+1;
37 }


Method: cellForRowAtIndexPath

//This is a call back invoked by the interface when drawing the table view. This method will create a cell for each
// row and add text to each cell dependeing on the string retrieved from the datasource. Note this is called for each
/index from zero to the number or rows returned by the previous method (numberOfRowsInSection). The zeroth
//row is hard coded to display the text "New Item" this is used to add new rows to the table.

38 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
39 {
//Try to get rusable cell
40 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
41 if (cell == nil)
42 {
//If not possible create a new cell
43 cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0,0,0,0) reuseIdentifier:@"CellIdentifier"]
autorelease];
44 cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
45 }

46 // Get the string to display and set the value in the cell
47 if(indexPath.row == 0)
48 {
//The first (or zeroth cell) contains a New Item string and is used to add elements to list
49 cell.text = @"New Item...";
50 }
51 else
52 {
//Retreive text from datasource, the -1 accounts for the first element being hardcoded to say new Item
53 cell.text = [dataController objectInListAtIndex:indexPath.row-1];
54 }
55 return cell;
56 }



Method: editingStyleForRowAtIndexPath

//This defines for each row its editing style, i.e. whether it shows a remove sign (Red circle with subtract sign) or
//and add sign (Green circle with addition sign). I have hard coded the first row (the one that says "New Item") to display the add sign and all others to display the subtract sign.

57 - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:
(NSIndexPath *)indexPath
58 {
59 if(indexPath.row == 0)
60 {
61 return UITableViewCellEditingStyleInsert;
62 }
63 else
64 {
65 return UITableViewCellEditingStyleDelete;
66 }
67 }



Method: commitEditingStyle
//This method is invoked when the user has finished editing one of the rows of the table. The three parameters
//respectivly proivide, the table being edited, the style of the row being edited (Add or Delete) and the row being
//edited. If the style is delete we remove the corresponding item from the data source and then delete the row from
///the view. If the style was add we add another element to the data source and relode the data into the table view.
//In reality add item will probably load a new view which allows the user to enter text but that is left to another
//tutorial for now we are hard coding the text to be added.

68 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
69 {
70 // If row is deleted, remove it from the list.
71 if (editingStyle == UITableViewCellEditingStyleDelete)
72 {
73 [dataController removeDataAtIndex:indexPath.row-1];
74 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
75 }
76 else if(editingStyle == UITableViewCellEditingStyleInsert)
77 {
78 [dataController addData:@"New Row Added"];
79 [tableView reloadData];
80 }
81 }


82 - (void)dealloc
83 {
84 [super dealloc];
85 }

86 @end

Step 5: Loading the TableView
In the TableViewTutorialAppDelegate.m file's applicationDidFinishLaunching method initialize the tableview controller and add it as a sub view. The code should look something like this.

1 - (void)applicationDidFinishLaunching:(UIApplication *)application
2 {
3 viewController = [[TableViewTutorialViewController alloc] initWithStyle:UITableViewStylePlain];
5 [window addSubview:viewController.view];
6 [window makeKeyAndVisible];
7 }

Step 6: Try it out

Wednesday 15 June 2011

How To Manage NSMutableDictionary And NSMutableArray

//create the dictionary
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

//add keyed data
[dictionary setObject:@"Object One" forKey:@"1"];
[dictionary setObject:@"Object Two" forKey:@"2"];
[dictionary setObject:@"Object Three" forKey:@"3"];

//write out Object Three to the log
NSLog(@"%@", [dictionary objectForKey:@"3"]);

//release the dictionary
[dictionary release];

//create the mutablearray
NSMutableArray *arrayOfObjects = [[NSMutableArray alloc] init];
[arrayOfObjects addObject:@"Object One"];
[arrayOfObjects addObject:@"Object Two"];
[arrayOfObjects addObject:@"Object Three"];
[arrayOfObjects addObject:@"Object Four"];
[arrayOfObjects addObject:@"Object Five"];

//write out Object to the log
NSLog(@"Object = %@", [arrayOfObjects objectAtIndex:object no]);

Tuesday 14 June 2011

How to select component from UIPickerView and display the next screen

This is the UIPickerView example. In this example we will see how to select any name from singlecomponentpicker and display the next screen. So let see how it will work.

This is the UIPickerView example. In this example we will see how to select any name from singlecomponentpicker and display the next screen. So let see how it will work.

Step 1: Open a Xcode, Create a View base application. Give the application name ”SingleComponentPicker”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: We need to add one UIViewController class in the project. So select the project -> New File -> Cocoa Touch -> ViewController subclass and give the class name “AnotherView”.

Step 4: Open the SingleComponentPickerViewController.h file and add UIPickerViewDataSouce and UIPickerViewDelegate protocal, import AnotherView class, UIPickerView and NSArray class and one buttonPressed method:. So make the following changes in the file:

#import
@class AnotherView;

@interface SingleComponentPickerViewController : UIViewController

{

AnotherView *anotherView;
IBOutlet UIPickerView *singlePicker;
NSArray *pickerData;
}

@property(nonatomic , retain) UIPickerView *singlePicker;
@property(nonatomic , retain) NSArray *pickerData;

-(IBAction)buttonPressed;

@end

Step 5: Double click .xib file and open it to interface Builder. Add a picker and a button to te View,and then make the necessary connections. Control drag File’s Owner to the picker view,and select singlePicker outlet. Then single click the picker, bring up connection inspector, you’ll see that the first two items are DataSource and Delegate. Drag from the circle next to DataSource to the File’s Owner icon. Do it once again, and connect Delegate to File’s Owner icon. Next drag a Round Rect Button to the view, double-click it, give it a title of Select. Connect to Touch Up Inside to File’s Owner and select buttonPressed action. Save the nib, and go back to Xcode.

Step 6: Now open the SingleComponentPickerViewController.m file and make the following changes in the file:

#import "SingleComponentPickerViewController.h"
#import "AnotherView.h"
@implementation SingleComponentPickerViewController
@synthesize singlePicker;
@synthesize pickerData;

// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}

-(IBAction)buttonPressed
{


anotherView = [[AnotherView alloc]
initWithNibName:@"AnotherView"
bundle:nil];
[self.view addSubview:anotherView.view];

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSArray *array = [[NSArray alloc] initWithObjects:@"Luke",@"Leia",@"Han",@"Chewbacca",@"Artoo",
@"Threepio",@"lando",nil];
self.pickerData = array;
[array release];
[super viewDidLoad];
}

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

- (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 {
[singlePicker release];
[pickerData release];
[super dealloc];
}

#pragma mark Picker data source methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [pickerData count];
}

#pragma mark Picker delegate method
-(NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return[pickerData objectAtIndex:row];
}
@end

Step 7: Open the AnotherView.h file and added UIButton class and BackButton method and import SingleComponentViewController class now make the following changes in the file.

#import
@class SingleComponentPickerViewController;

@interface AnotherView : UIViewController {

SingleComponentPickerViewController *singleComponentView;

UIButton *backButton;

}

@property (nonatomic, retain) UIButton *backButton;

-(IBAction)backButton :(id)sender;

@end

Step 8: Double click the AnotherView.xib file and open it to the Interface Builder. First drag the label and Button from the library and place it to the View window. Select the label and bring up attribute inspector and change the label name “Another View”, select the button and bring up connection inspector and drag Touch Up Inside to the File’s Owner icon and select BackButton: method. Now save it close it and go back to the Xcode.

Step 9: Open the AnotherView.m file and make the following changes:

#import "AnotherView.h"
#import "SingleComponentPickerViewController.h"
@implementation AnotherView

@synthesize backButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

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

- (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.
}

-(IBAction)backButton :(id)sender

{
singleComponentView = [[SingleComponentPickerViewController alloc]
initWithNibName:@"SingleComponentPickerViewController"bundle:nil];

[self.view addSubview:singleComponentView.view];
[singleComponentView.view release];}

#pragma mark – View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

Step 10: Now compile and run the application in the Simulator.

How to Adding data using SQLite for iPhone

This is the Sqlite database app. Some times your app may have the need to store data in some kind of database. In iPhone application you can do so using SQLite.

This is the Sqlite database app. Some times your app may have the need to store data in some kind of database. In iPhone application you can do so using SQLite.

Step 1: Open the Xcode and create a new Xcode project using Navigation base application template. Give the application name “SQL”. As shown in the figure below:



Step 2: Expand classes and notice Interface Builder created the RootViewController.h and RootViewController.m class for you. Expand Resources and notice the template generated a separate nib, RootViewController.xib.

Step 3: To create database in sqlite follow the below steps:
Now that the terminal is open let’s create the database. This is done with the command:

sqlite3 Datalist.sqlite
SQLite3 will now start and load the Datalist.sqlite database. By default the database is empty and contains no tables.
We only need to create one table. We will create a table called Datalist by typing the following statement:

CREATE TABLE Datalist(pk INTEGER PRIMARY KEY, name VARCHAR(25), age INTEGER);
One thing to note here is the pk field. It is the primary key of the table.
Now that our table has been created, let’s add some data. Type the following commands below.

INSERT INTO Datalist(name,age) VALUES(‘vishal’,29);
INSERT INTO Datalist(name,age) VALUES(‘nilesh’,30);
INSERT INTO Datalist(name,age) VALUES(‘vinod’,28);
INSERT INTO Datalist(name,age) VALUES(‘amrita’,25);
Your terminal window will look something as shown below:



Now go back to XCode. Do a Control-Click (right click) on the folder named Resources. Click Add -> Existing Files… and browse to your Datalist.sqlite file and click Add. It will then prompt you with a screen as shown below:



Step 4: Now that we have added the database, we need to load the Objective C libraries so we can use it. Do a control-click (right click) on the Frameworks folder. Click Add -> Existing Frameworks. So in the search bar type in libsqlite3. The file we are looking for is called libsqlite3.0.dylib.



Step 5: We need to add another file. Right-click on the Classes folder and choose Add -> New File. Under Cocoa Touch Class category choose Objective-C class. Name it SqlA.h and SqlA.m file.
This will be a very simple class that will take our dummy data file, read it in as an NSArray and provide some utility methods to access the data from the file.

@interface SqlA: NSObject {
NSInteger age;
NSString *name;
//Internal variables to keep track of the state of the object.
BOOL isDirty;
BOOL isDetailViewHydrated;
}

@property (nonatomic, readonly) NSInteger age;
@property (nonatomic, copy) NSString *name;

@property (nonatomic, readwrite) BOOL isDirty;
@property (nonatomic, readwrite) BOOL isDetailViewHydrated;

//Static methods.
+ (void) getInitialDataToDisplay:(NSString *)dbPath;
+ (void) finalizeStatements;

//Instance methods.
- (id) initWithPrimaryKey:(NSInteger)pk;

@end

Step 6: Open the SqlA.m file and make the following changes in the file.

#import "SqlA.h"
static sqlite3 *database = nil;

@implementation SqlA

@synthesize name,age,isDirty, isDetailViewHydrated;

+ (void) getInitialDataToDisplay:(NSString *)dbPath {

SQLAppDelegate *appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication] delegate];

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

const char *sql = "select name,age from Datalist";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {

while(sqlite3_step(selectstmt) == SQLITE_ROW) {

NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
SqlA *coffeeObj = [[SqlA alloc] initWithPrimaryKey:primaryKey];
coffeeObj.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];

coffeeObj.isDirty = NO;

[appDelegate.coffeeArray addObject:coffeeObj];
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}

+ (void) finalizeStatements {
if(database) sqlite3_close(database);
}

- (id) initWithPrimaryKey:(NSInteger) pk {
[super init];
age = pk;

isDetailViewHydrated = NO;

return self;
}

Step 7: Open the RootViewController.h file and make the following changes in the file.

@class SqlA;
@interface RootViewController : UITableViewController {
SQLAppDelegate *appDelegate;
}
@end

Step 8: Open the RootViewController.m file and make the following changes in the file.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [appDelegate.coffeeArray count];
}
- (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];
}
//Get the object from the array.
SqlA *coffeeObj = [appDelegate.coffeeArray objectAtIndex:indexPath.row];

//Set the coffename.
cell.text = coffeeObj.name;

// Set up the cell
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic — create and push a new view controller
}
- (void)viewDidLoad {
[super viewDidLoad];

self.navigationItem.rightBarButtonItem = self.editButtonItem;

appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication] delegate];

self.title = @"Name List";
}

Step 9: Open the SQLAppDelegate.h file and make the following changes in the file.

@class SqlA;
@interface SQLAppDelegate : NSObject {
UIWindow *window;
UINavigationController *navigationController;

//To hold a list of Coffee objects
NSMutableArray *coffeeArray;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) NSMutableArray *coffeeArray;

- (void) copyDatabaseIfNeeded;
- (NSString *) getDBPath;

Step 10: Open the SQLAppDelegate.m file and make the following changes in the file.

- (void) copyDatabaseIfNeeded {

//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Datalist.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

if (!success)
NSAssert1(0, @"Failed to create writable database file with message ‘%@’.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"Datalist.sqlite"];
}

Step 11: Now compile and Run the code and get the final output.



You can download source code from here SQL

How to Show a UIAlertView

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Alert Succesfull." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: @"Cancel", nil];
[alert show];
[alert release];

How To Parsing Data Using XMLParser

Parsing an XML file
This is the “XMLParsing” example. In this app we will read data from xml file and display the data on the screen.

This is the “XMLParsing” example. In this app we will read data from xml file and display the data on the screen.

Step 1: Open the Xcode and create a new Xcode project using Navigation base application template. Give the application name “XML”. As shown in the figure below:



Step 2: Expand classes and notice Interface Builder created the RootViewController.h and RootViewController.m class for you. Expand Resources and notice the template generated a separate nib, RootViewController.xib.

Step 3: We need to add another file. Right-click on the Classes folder and choose Add -> New File. Under Cocoa Touch Class category choose Objective-C class. Name it Book.h and Book.m file.
This will be a very simple class that will take our dummy data file, read it in as an NSArray and provide some utility methods to access the data from the file.

#import
@interface Book : NSObject {

NSInteger bookID;
NSString *name; //Same name as the Entity Name.
NSString *address; //Same name as the Entity Name.
NSString *country; //Same name as the Entity Name.

}
@property (nonatomic, readwrite) NSInteger bookID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *address;
@property (nonatomic, retain) NSString *country;

@end

Step 4: We need to add Book.m file.

#import "Book.h"
@implementation Book
@synthesize name, address, country, bookID;
- (void) dealloc {

[country release];
[address release];
[name release];
[super dealloc];
}
@end

Step 5: We need to add another file. Right-click on the Resource folder and choose Add -> New File. Under Resource category choose View-XIB class. Name it BookDetailView.xib file. Double click the file and select Grouped table view.



Step 6: We need to add another file. Right-click on the Classes folder and choose Add -> New File. Under Cocoa Touch Class category choose Objective-C class. Name it XMLParser.h and XMLParser.m file. This will be a very simple class that will take our dummy data file, read it in as an NSArray and provide some utility methods to access the data from the file.

#import
@class XMLAppDelegate, Book;

@interface XMLParser : NSObject {

NSMutableString *currentElementValue;

XMLAppDelegate *appDelegate;
Book *aBook;
}

- (XMLParser *) initXMLParser;

@end

Step 7: We need to open XMLParser.m file.

#import "XMLParser.h"
#import "XMLAppDelegate.h"
#import "Book.h"
@implementation XMLParser

- (XMLParser *) initXMLParser {

[super init];

appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate];

return self;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {

if([elementName isEqualToString:@"Books"]) {
//Initialize the array.
appDelegate.books = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"Book"]) {

//Initialize the book.
aBook = [[Book alloc] init];

//Extract the attribute here.
aBook.bookID = [[attributeDict objectForKey:@"id"] integerValue];

NSLog(@"Reading id value :%i", aBook.bookID);
}

NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];

NSLog(@"Processing Value: %@", currentElementValue);

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

if([elementName isEqualToString:@"Books"])
return;

//There is nothing to do if we encounter the Books element here.
//If we encounter the Book element howevere, we want to add the book object to the array
// and release the object.
if([elementName isEqualToString:@"Book"]) {
[appDelegate.books addObject:aBook];

[aBook release];
aBook = nil;
}
else
[aBook setValue:currentElementValue forKey:elementName];

[currentElementValue release];
currentElementValue = nil;
}

- (void) dealloc {

[aBook release];
[currentElementValue release];
[super dealloc];
}

@end

Step 8: We need to add another file. Right-click on the Classes folder and choose Add -> New File. Under Cocoa Touch Class category choose UIViewController class. Name it BookDetailViewController.h and BookDetailViewController.m file.

#import
@class Book;

@interface BookDetailViewController : UIViewController {

IBOutlet UITableView *tableView;

Book *aBook;
}

@property (nonatomic, retain) Book *aBook;

@end

Step 9: We need to open BookDetailViewController.m file.

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

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
switch(indexPath.section)
{
case 0:
cell.text = aBook.name;
break;
case 1:
cell.text = aBook.address;
break;
case 2:
cell.text = aBook.country;
break;
}
return cell;
}
- (NSString *)tableView:(UITableView *)tblView titleForHeaderInSection:(NSInteger)section {

NSString *sectionName = nil;

switch(section)
{
case 0:
sectionName = [NSString stringWithString:@"Name"];
break;
case 1:
sectionName = [NSString stringWithString:@"Address"];
break;
case 2:
sectionName = [NSString stringWithString:@"Country"];
break;
}
return sectionName;
}

Step 10: We need to open XmlAppDelegate.h file.

#import
@interface XMLAppDelegate : NSObject {

UIWindow *window;
UINavigationController *navigationController;

NSMutableArray *books;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) NSMutableArray *books;

@end

Step 11: We need to open XmlAppDelegate.m file.

#import "XMLAppDelegate.h"
#import "RootViewController.h"
#import "XMLParser.h"
@implementation XMLAppDelegate

@synthesize window;
@synthesize navigationController, books;

- (void)applicationDidFinishLaunching:(UIApplication *)application {


NSURL *url = [[NSURL alloc] initWithString:@"http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];

//Set delegate
[xmlParser setDelegate:parser];

//Start parsing the XML file.
BOOL success = [xmlParser parse];

if(success)
NSLog(@"No Errors");
else
NSLog(@"Error Error Error!!!");

// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}

Step 12: Now build and run the code and view the Output in the Simulator.

Thursday 9 June 2011

How to Customize UINavigationBar and Item

self.navigationItem.title = @" Apple ";
Object.navigationBar.barStyle = UIBarStyleBlackTranslucent;
Object.navigationBar.barStyle = UIBarStyleBlackOpaque;
Object.navigationBar.barStyle = UIBarStyleBlack;
Object.navigationBar.barStyle = UIBarStyleBlackDefault;
– pushViewController:animated:
– popViewControllerAnimated:
– popToViewController:animated:
– popToRootViewControllerAnimated:

– setToolbarHidden:animated:
setToolbarItems:animated:
hidesBottomBarWhenPushed
setNavigationBarHidden:animated:

[self.navigationController pushViewController:targetViewController animated:YES];
[self.navigationController popViewController:targetViewController animated:YES];
[self.navigationController rootViewController:targetViewController animated:YES];


[self presentModalViewController:infocontroller animated:YES];

UIBarButtonItem *btnAddBuzz = [[[UIBarButtonItem alloc] initWithTitle:@"Add Buzz" style:UIBarButtonItemStyleBordered target:self action:@selector (ClickAddBuzz)] autorelease];

self.navigationItem.rightBarButtonItem = btnAddBuzz;
self.navigationItem.leftBarButtonItem = btnAddBuzz;

UIBarButtonSystemItemDone,
UIBarButtonSystemItemCancel,
UIBarButtonSystemItemEdit,
UIBarButtonSystemItemSave,
UIBarButtonSystemItemAdd,
UIBarButtonSystemItemFlexibleSpace,
UIBarButtonSystemItemFixedSpace,
UIBarButtonSystemItemCompose,
UIBarButtonSystemItemReply,
UIBarButtonSystemItemAction,
UIBarButtonSystemItemOrganize,
UIBarButtonSystemItemBookmarks,
UIBarButtonSystemItemSearch,
UIBarButtonSystemItemRefresh,
UIBarButtonSystemItemStop,
UIBarButtonSystemItemCamera,
UIBarButtonSystemItemTrash,
UIBarButtonSystemItemPlay,
UIBarButtonSystemItemPause,
UIBarButtonSystemItemRewind,
UIBarButtonSystemItemFastForward,
UIBarButtonSystemItemUndo,
UIBarButtonSystemItemRedo,
UIBarButtonSystemItemPageCurl,

How to Show a OneTime SubView On The MainView

#import

@interface Home : UIView
{
}
@end

#import "Home.h"

@implementation Home

- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
- (void)dealloc
{
[super dealloc];
}
@end

#import
@interface AgentWorldViewController : UITabBarController
{
UIView *HomePage;
}
-(void)RemoveHomePageView;

@end

#import "AgentWorldViewController.h"
#import "Home.h"
#import "AgentClosest.h"
#import "BuzzView.h"
#import "SocialMedia.h"

@implementation AgentWorldViewController

- (void)viewDidLoad
{
[super viewDidLoad];
//Create view for find an Agent
UINavigationController *agentNC = [[UINavigationController alloc] init];
AgentClosest *agentVC = [[AgentClosest alloc] init];
agentVC.tabBarItem.title = @"Find an Agent";
agentVC.tabBarItem.image = [UIImage imageNamed:@"Newnavigation_findAgent.png"];
agentVC.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Newbackground.png"]];
agentNC.viewControllers = [NSArray arrayWithObjects:agentVC, nil];
agentNC.navigationBar.barStyle = UIBarStyleBlackTranslucent;

//Create view for Real Estate News
UINavigationController *oBuzzNC = [[UINavigationController alloc]init];
BuzzView *oBuzz = [[BuzzView alloc] init];
oBuzz.tabBarItem.title = @"Real Estate News";
oBuzz.tabBarItem.image = [UIImage imageNamed:@"Newnavigation_rNews.png"];
oBuzz.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Newbackground.png"]];
oBuzzNC.viewControllers = [NSArray arrayWithObjects:oBuzz, nil];
oBuzzNC.navigationBar.barStyle = UIBarStyleBlackTranslucent;

//Create view for Social Media and Network
UINavigationController *oSettingNC = [[UINavigationController alloc] init];
SocialMedia *oSetting = [[SocialMedia alloc] init];
oSetting.tabBarItem.title = @"Social Media";
oSetting.tabBarItem.image = [UIImage imageNamed:@"Newnavigation_settings.png"];
oSetting.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"NewdistSettings_background.png"]];
oSettingNC.viewControllers = [NSArray arrayWithObjects:oSetting, nil];
oSettingNC.navigationBar.barStyle = UIBarStyleBlackTranslucent;

self.viewControllers = [NSArray arrayWithObjects:agentNC, oBuzzNC, oSettingNC, nil];
[agentNC release];
[agentVC release];
[oBuzz release];
[oSetting release];

self.tabBarItem=[[UITabBarItem alloc]initWithTabBarSystemItem: UITabBarSystemItemBookmarks tag:0];

CGRect apprect = [[UIScreen mainScreen] applicationFrame];
HomePage = [[UIView alloc] initWithFrame:apprect];
UIImageView *HomePageBackgroud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Newbackground.png"]];
HomePageBackgroud.frame = apprect;
[self.view addSubview:HomePageBackgroud];
[HomePageBackgroud release];

UIButton *btnFindAgent = [UIButton buttonWithType:UIButtonTypeCustom];
[btnFindAgent setImage:[UIImage imageNamed:@"Newhome_findAgent.png"] forState:UIControlStateNormal];
[btnFindAgent setFrame:CGRectMake(120.0f, 90.0f, 64.0f, 64.0f)];
btnFindAgent.tag = 0;
[btnFindAgent addTarget:self action:@selector(HomePageButton_Click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnFindAgent];

UILabel *findAgentlbl=[[UILabel alloc]initWithFrame:CGRectMake(117.0f, 160.0f, 80.0, 10.0)] ;
findAgentlbl.text=@"Find an Agent";
[findAgentlbl setBackgroundColor:[UIColor clearColor]];
findAgentlbl.font=[UIFont fontWithName:@"Helvetica-Bold" size:10];
findAgentlbl.textColor=[UIColor whiteColor];
[self.view addSubview:findAgentlbl];
[findAgentlbl release];

UIButton *btnRealStateNews = [UIButton buttonWithType:UIButtonTypeCustom];
[btnRealStateNews setImage:[UIImage imageNamed:@"Newhome_rNews.png"] forState:UIControlStateNormal];
[btnRealStateNews setFrame:CGRectMake(120.0f, 205.0f, 64.0f, 64.0f)];
btnRealStateNews.tag =1;
[btnRealStateNews addTarget:self action:@selector(HomePageButton_Click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnRealStateNews];

UILabel *RealStatelbl=[[UILabel alloc]initWithFrame:CGRectMake(110.0, 275.0, 90.0, 10.0)];
RealStatelbl.text=@"Real Estate News";
[RealStatelbl setBackgroundColor:[UIColor clearColor]];
RealStatelbl.font=[UIFont fontWithName:@"Helvetica-Bold" size:10];
RealStatelbl.textColor=[UIColor whiteColor];
[self.view addSubview:RealStatelbl];
[RealStatelbl release];

UIButton *btnSetting = [UIButton buttonWithType:UIButtonTypeCustom];
[btnSetting setImage:[UIImage imageNamed:@"Newhome_settings.png"] forState:UIControlStateNormal];
[btnSetting setFrame:CGRectMake(120.0f, 325.0f, 64.0f, 64.0f)];
btnSetting.tag = 2;
[btnSetting addTarget:self action:@selector(HomePageButton_Click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnSetting];
}

- (void)InfoButton:(id)sender
{
InfoViewController *infocontroller=[[InfoViewController alloc]init];
[self presentModalViewController:infocontroller animated:YES];
}
- (void)HomePageButton_Click:(id)sender
{
UIButton *btnTemp = sender;
if (btnTemp.tag == 0)
{
self.selectedIndex = 0;
[self RemoveHomePageView];
}
else if (btnTemp.tag == 1)
{
self.selectedIndex = 1;
[self RemoveHomePageView];
}
else
{
self.selectedIndex = 2;
[self RemoveHomePageView];
}
}

-(void)RemoveHomePageView
{

UIImageView *vHomePage;
UIButton *bButton;
UILabel *lLabel;
for (NSInteger i=[[self.view subviews] count] -1 ; i>= 0; i--)
{
if ([[[self.view subviews] objectAtIndex:i] isKindOfClass:[UIImageView class]])
{
vHomePage=[[self.view subviews] objectAtIndex:i];
[vHomePage removeFromSuperview];
vHomePage=nil;
}
else if ([[[self.view subviews] objectAtIndex:i] isKindOfClass:[UIButton class]])
{
bButton = [[self.view subviews] objectAtIndex:i];
[bButton removeFromSuperview];
bButton = nil;
}
else if ([[[self.view subviews] objectAtIndex:i] isKindOfClass:[UILabel class]])
{
lLabel = [[self.view subviews] objectAtIndex:i];
[lLabel removeFromSuperview];
lLabel = nil;
}

}

}
- (IBAction)RealStateNews
{

}
- (void) locationManager: (CLLocationManager *) manager didUpdateToLocation: (CLLocation *) newLocation fromLocation: (CLLocation *) oldLocation
{

NSString *lat = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.latitude];

NSLog(lat);
NSString *lng = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.longitude];

NSLog(lng);
NSString *acc = [[NSString alloc] initWithFormat:@"%g", newLocation.horizontalAccuracy];

NSLog(acc);

[acc release];
[lat release];
[lng release];

MKCoordinateSpan span;
span.latitudeDelta=newLocation.coordinate.latitude;
span.longitudeDelta=newLocation.coordinate.longitude;

MKCoordinateRegion region;
region.center = newLocation.coordinate;
region.span=span;
}
- (void) locationManager: (CLLocationManager *) manager didFailWithError: (NSError *) error
{
NSString *msg = [[NSString alloc] initWithString:@"Error obtaining location"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle: @"Done" otherButtonTitles:nil];
[alert show];
[msg release];
[alert release];
}

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

- (void)viewDidUnload
{
}
- (void)dealloc
{
[HomePage release];
[super dealloc];
}

@end

Wednesday 8 June 2011

How to Create a Tabbar View.

#import

@interface TabBarAppDelegate : NSObject
{
UIWindow *window;
UITabBarController *tabBarControl;
}
@property (nonatomic, retain) UITabBarController *tabBarControl;
@property (nonatomic, retain) IBOutlet UIWindow *window;

@end


#import "TabBarAppDelegate.h"
#import "ViewController1.h"
#import "ViewController2.h"
#import "ViewController3.h"

@implementation TabBarAppDelegate

@synthesize window,tabBarControl;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[window makeKeyAndVisible];
self.tabBarControl=[[UITabBarController alloc]init];
ViewController1 *tv1 = [[tabview3 alloc]init];
tv.tabBarItem.title = @"TabView1";
tv.tabBarItem.image = [UIImage imageNamed:@"Item1.png"];
ViewController2 *tv2 = [[tabview1 alloc]init];
tv1.tabBarItem.title = @"TabView2";
tv1.tabBarItem.image = [UIImage imageNamed:@"Item2.png"];
ViewController3 *tv3 = [[tabview2 alloc]init];
tv2.tabBarItem.title = @"TabView3";
tv2.tabBarItem.image = [UIImage imageNamed:@"Item3.png"];
[self.tabBarControl setViewControllers:[NSArray arrayWithObjects:tv1, tv2,tv3,nil]];
[window addSubview:tabBarControl.view];

[tv release];
[tv1 release];
[tv2 release];
[tabBarControl release];
return YES;
}

How to Create Image,Label,Button,Textfield,ScrollView.

UIImageView *LogoImage=[[UIImageView alloc]initWithFrame:CGRectMake(100.0,0.0 ,100.0, 60.0)];
[LogoImage setImage:[UIImage imageNamed:@"Logo.png"]];
[self.view addSubview:LogoImage];
[LogoImage release];

UILabel *addressLabel=[[UILabel alloc]initWithFrame:CGRectMake(10.0,123.0, 115.0, 100)] ;
addressLabel.text=@"iPhone";
[addressLabel setBackgroundColor:[UIColor clearColor]];
addressLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
addressLabel.textAlignment= UITextAlignmentCenter;
addressLabel.textColor=[UIColor purpleColor];
[self.view addSubview:addressLabel];
[addressLabel release];

UIButton *GetDirectionButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
GetDirectionButton.frame=CGRectMake(30.0, 380.0, 100.0, 25.0);
[GetDirectionButton setBackgroundColor:[UIColor redColor]];
[GetDirectionButton setTitle:@"Go Apple" forState:UIControlStateNormal];
[GetDirectionButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
GetDirectionButton.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
[GetDirectionButton addTarget:self action:@selector(GetDirectionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:GetDirectionButton];

UITextField *txtZipCode = [[UITextField alloc]initWithFrame:CGRectMake(28, 230, 265, 40)];
txtZipCode.borderStyle = UITextBorderStyleBezel;
txtZipCode.textColor = [UIColor blackColor];
txtZipCode.font = [UIFont systemFontOfSize:17];
txtZipCode.placeholder = @"Enter Zip Code";
txtZipCode.backgroundColor = [UIColor whiteColor];
txtZipCode.autocorrectionType = UITextAutocorrectionTypeNo;
txtZipCode.textAlignment = UITextAlignmentCenter;
txtZipCode.keyboardType = UIKeyboardTypeDefault;
txtZipCode.returnKeyType = UIReturnKeyDefault;
txtZipCode.clearButtonMode = UITextFieldViewModeWhileEditing;
txtZipCode.delegate = self;
txtZipCode.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[scrollview addSubview:txtZipCode];
[txtZipCode release];

UIScrollView *scrollview =[[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 480)];
scrollview.contentSize=CGSizeMake(320,563);
[scrollview setBackgroundColor:[UIColor blackColor]];
scrollview.clipsToBounds=YES;
scrollview.contentOffset=CGPointMake(0.0,0.0);
scrollview.contentInset=UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
scrollview.scrollEnabled=YES;
[self.view addSubview:scrollview];

How to Create a GroupedStyle Table View

@interface WhatWeDoViewController : UIViewController
{
UITableView *tableview;
}
@property(nonatomic ,retain) UITableView *tableview;
@end

#import "WhatWeDoViewController.h"
@implementation WhatWeDoViewController
@synthesize tableview;

- (void)viewDidLoad
{
[super viewDidLoad];
tableview=[[UITableView alloc]initWithFrame:CGRectMake(3,125.0, self.view.bounds.size.width-5, 300.0)style:UITableViewStyleGrouped];
tableview.delegate = self;
tableview.dataSource = self;
tableview.autoresizesSubviews = YES;
tableview.backgroundColor=[UIColor clearColor];
tableview.alpha=0.7;
UIColor *separator = [[UIColor alloc] initWithRed:49.0 green:62.0 blue:0.0 alpha:1.0];
tableview.separatorColor = separator;
[self.view addSubview:tableview];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// The number of sections is based on the number of items in the data property list.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 4;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:nil ] autorelease];
cell.backgroundColor=[UIColor grayColor];
cell.alpha=0.5;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Add label into cell
UILabel *titleLabel =[[UILabel alloc]initWithFrame:CGRectMake(10.0, 5.0, cell.contentView.bounds.size.width, 40.0)];
titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:18];
titleLabel.backgroundColor=[UIColor clearColor];
titleLabel.textColor=[UIColor purpleColor];
titleLabel.opaque = YES;
[cell.contentView addSubview:titleLabel];

if(indexPath.row==0)
{
titleLabel.text= @"Software Development";
}
if(indexPath.row==1)
{
titleLabel.text= @"Research & Development";
}
if(indexPath.row==2)
{
titleLabel.text= @"Industries Served";
}
if(indexPath.row==3)
{
titleLabel.text= @"Functional Offering";
}
return cell;
[titleLabel release];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//Row selection
if(indexPath.row==0)
{
TechnologyViewController *myController=[[TechnologyViewController alloc]init];
[[self navigationController] pushViewController:myController animated:YES];
myController.title = @"Development";
}
if(indexPath.row==1)
{
ResearchViewController *myController=[[ResearchViewController alloc]init];
[[self navigationController] pushViewController:myController animated:YES];
}
if(indexPath.row==2)
{
IndustriesViewController *myController=[[IndustriesViewController alloc]init];
[[self navigationController] pushViewController:myController animated:YES];
}
if(indexPath.row==3)
{
FunctionalViewController *myController=[[FunctionalViewController alloc]init];
[[self navigationController] pushViewController:myController animated:YES];
}
}

Clicking The Button Show Another View

- (void)viewDidLoad
{
UIButton *whoButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
whoButton.frame=CGRectMake(20.0, 240.0, 80.0, 25.0);
[whoButton setBackgroundColor:[UIColor blueColor]];
[whoButton setTitle:@"WHO" forState:UIControlStateNormal];
[whoButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
whoButton.font=[UIFont fontWithName:@"HelveticaNeue-Bold" size:12];
[whoButton addTarget:self action:@selector(whoButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:whoButton];
}
-(void)whoButton:(id)sender
{
WhoWeAreViewController *WhoWeAreUsController=[[WhoWeAreViewController alloc]init];
[[self navigationController] pushViewController:WhoWeAreUsController animated:YES];
}

How To Customise The Button

UIButton *kunalImgButton = [UIButton buttonWithType:UIButtonTypeCustom];
[kunalImgButton setImage:[UIImage imageNamed:@"kunal.png"] forState:UIControlStateNormal];
[kunalImgButton setFrame:CGRectMake(10.0,180.0 ,79.0, 90.0)];
[kunalImgButton addTarget:self action:@selector(kunalButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:kunalImgButton];

How To Animated Image on the View.

- (void)viewDidLoad
{
[super viewDidLoad];
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0.0,0.0 ,320.0, 213.0)];
imageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"Infra.jpg"],
[UIImage imageNamed:@"ArcGate.jpg"],
[UIImage imageNamed:@"Infra.jpg"],nil];
imageView.animationRepeatCount = 67;
imageView.animationDuration = 30;
[imageView startAnimating];
[self.view addSubview:imageView];
[imageView release];
}

How to Use NavigationController with Appdelegete and ViewController.

#import < UIKit/UIKit.h >

@interface SampleAppDelegate : NSObject
{
UIWindow *window;
UINavigationController *navigationcontroller;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationcontroller;
@end


#import " SampleAppDelegate.h "
#import "MainScreenViewController.h"

@implementation SampleAppDelegate

@synthesize window,navigationcontroller;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[window makeKeyAndVisible];
MainScreenViewController *MVC = [[MainScreenViewController alloc]init];
navigationcontroller = [[UINavigationController alloc]initWithRootViewController:MVC];
[MVC release];
[window addSubview:[navigationcontroller view]];
return YES;
}
- (void)dealloc
{
[window release];
[super dealloc];
}
@end

#import < UIKit/UIKit.h >

@interface MainScreenViewController : UIViewController
{
}
@end

#import "MainScreenViewController.h"

@implementation MainScreenViewController

- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"Home";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];

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

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

@end

Tuesday 7 June 2011

How to Implement Appdelegate to a Viewcontroller Using SplashScreen.



#import <UIKit/UIKit.h>

@class SplashScreenViewController;

@interface ExampleAppDelegate : NSObject <UIApplicationDelegate>
{
    UIWindow *window;
SplashScreenViewController *splashScreen;
BOOL shouldLoadSplashScreen;
UIImageView *imageView;
id lastViewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) id lastViewController;
-(void)setCurrentView:(UIViewController*)viewControllerObj;

@end

#import "ExampleAppDelegate.h"
#import "SplashScreenViewController.h"
#import "LoginViewController.h"

@implementation ExampleAppDelegate

@synthesize window;

@synthesize lastViewController;

-(void)setCurrentView:(UIViewController*)currentViewControllerObj
{
[[(UIViewController*)self.lastViewController view] removeFromSuperview];
self.lastViewController = currentViewControllerObj;
[self.window addSubview:currentViewControllerObj.view];
}

-(void)loadMenuScreen
{
[imageView removeFromSuperview];
LoginViewController *menuViewController = [[LoginViewController alloc] init];
[self.window addSubview:menuViewController.view];
self.lastViewController = menuViewController;
}

-(void)loadSplashScreen
{
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 768, 1024)];
[imageView setImage:[UIImage imageNamed:@"SplashScreen.png"]];
[self.window addSubview:imageView];
[imageView release];
[self performSelector:@selector(loadMenuScreen) withObject:nil afterDelay:3.0];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{    
    
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[self loadSplashScreen];
    [self.window makeKeyAndVisible];
return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application 
{
   shouldLoadSplashScreen = YES;
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application 
{
    
}
- (void)dealloc 
{
    [window release];
    [super dealloc];
}
@end

#import <UIKit/UIKit.h>
@interface SplashScreenViewController : UIViewController
{

}
@end

#import "SplashScreenViewController.h"
@implementation SplashScreenViewController

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


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return ((interfaceOrientation ==UIInterfaceOrientationLandscapeLeft) ||       (interfaceOrientation == UIInterfaceOrientationLandscapeRight ));
}


- (void)didReceiveMemoryWarning 
{
    [super didReceiveMemoryWarning];
}
- (void)viewDidUnload 
{
    [super viewDidUnload];
}
- (void)dealloc 
{
    [super dealloc];
}
@end

#import <UIKit/UIKit.h>

@interface LoginViewController : UIViewController <UITextFieldDelegate,UIAlertViewDelegate>
{
UITextField *IDtextFld;
UITextField *PaswordtextFld;
}

@end


#import "LoginViewController.h"
#import "OutletDetailsViewController.h"
#import "ExampleAppDelegate.h"

@implementation LoginViewController

- (void)viewDidLoad 
{
    [super viewDidLoad];
IDtextFld = [[UITextField alloc]initWithFrame:CGRectMake(420, 348, 420, 50)];
[IDtextFld setDelegate:self];
[IDtextFld setBorderStyle:UITextBorderStyleLine];
[IDtextFld setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:IDtextFld];
[IDtextFld release];
PaswordtextFld= [[UITextField alloc]initWithFrame:CGRectMake(420, 432, 423, 52)];
[PaswordtextFld setDelegate:self];
[PaswordtextFld setBorderStyle:UITextBorderStyleLine];
[self.view addSubview:PaswordtextFld];
[PaswordtextFld release];
UIButton *SubmitButton = [UIButton buttonWithType:UIButtonTypeCustom];
[SubmitButton setImage:[UIImage imageNamed:@"LgnSubmitBtn.png"]   forState:UIControlStateNormal];
[SubmitButton setFrame:CGRectMake(455, 547, 215, 63)];
[SubmitButton addTarget:self action:@selector(SubmitButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:SubmitButton];
}
-(void)SubmitButton:(id)sender
{
NSString *Id = IDtextFld.text ;
NSLog(@"ID is ==>>%@",Id);
NSString *pwd = PaswordtextFld.text ;
NSLog(@"Password ==>>%@",pwd);
OutletDetailsViewController *odvObject = [[OutletDetailsViewController alloc] init];
ExampleAppDelegate *delegate = (ExampleAppDelegate*)[[UIApplication sharedApplication]delegate];
[delegate setCurrentView:odvObject];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
return ((interfaceOrientation ==UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight ));
}


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


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