Search Posts in my Blog

Showing posts with label iphone. Show all posts
Showing posts with label iphone. Show all posts

Thursday, 19 September 2013

SQLite Demo

1. Project Requirements
I suggest that you have at least a basic understanding of SQLite, writing SQL statements, the XCode interface and using the terminal in OSX. If you don’t know anything about any of these topics then this tutorial probably isn’t for you.


2. Creating our SQLite database for our tutorial
We first need to create a database for use with our application. For the purposes of this tutorial we will be building a database of animals along with a little information on them and a picture.
Fire up a new Terminal window and make a new folder to store the database in, here are the commands I ran


cd /Users/lookaflyingdonkey/Documents
mkdir SQLiteTutorial
cd SQLiteTutorial
sqlite3 AnimalDatabase.sql


You should now be at a “sqlite” command prompt, this is where we will be building our database structure and entering some test data.
For our example we need the name of the animal, a short description and a link to an image. Follow the commands below to create the table and to enter some sample data.

CREATE TABLE animals ( id INTEGER PRIMARY KEY, name VARCHAR(50), description TEXT, image VARCHAR(255) );

INSERT INTO animals (name, description, image) VALUES ('Elephant', 'The elephant is a very large animal that lives in Africa and Asia', 'http://dblog.com.au/wp-content/elephant.jpg');
INSERT INTO animals (name, description, image) VALUES ('Monkey', 'Monkies can be VERY naughty and often steal clothing from unsuspecting tourists', 'http://dblog.com.au/wp-content/monkey.jpg');
INSERT INTO animals (name, description, image) VALUES ('Galah', 'Galahs are a wonderful bird and they make a great pet (I should know, I have one)', 'http://dblog.com.au/wp-content/galah.jpg');
INSERT INTO animals (name, description, image) VALUES ('Kangaroo', 'Well I had to add the Kangaroo as they are the essence of the Australian image', 'http://dblog.com.au/wp-content/kangaroo.jpg');


The first command will create the table with the required structure and the next four will insert some test data for us to work with. To ensure that you have entered the data correctly you can execute “SELECT * FROM animals;” and see if it returns the items above. Once you are confident that everything had been created successfully you can leave the sqlite command line by typing “.quit”.


3. Creating our Project
Now that our database is all ready to go we need to setup our X-Code project.
Start off by creating a new “Empty Application”.

Give your Project a name, I called mine “SQLiteTutorial”.

Right Click on the “Supporting Files” folder in the left hand pane and click “Add File”, we want to create a new “ViewController”.


4. Adding SQLite Framework and our Animal Database
Now that we have created all of our views and classes it is time to start the real grunt work.
First we need to include the SQLite libraries so our application can utilise them. To do this you will need to click on the project name in the left hand pane, then click on “Targets > Build Phases > Link binaries… > click on plus signand add  libsqlite3.0.dylib” 

We also need to add our database we created earlier . To do this simply right click on the “Supporting Files” , click “Add > Existing Files…”, navigate to the location you created the database in then double click on the AnimalDatabase.sql file. Another popup will appear, just click add.
All done with the importing, time to code!


5. The Coding begins!
We are going to start the coding by building our “Animal” object, every animal will have 3 properties, a name, a description and an image URL.
Open up the “Animal.h” file from the “Classes” folder and edit its contents to look like below,

#import <UIKit/UIKit.h>

@interface Animal : NSObject {
NSString *name;
NSString *description;
NSString *imageURL;
}

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *imageURL;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u;

@end


Most of the above code should be pretty familiar to you, the only thing that may not be is the initWithName line, this line will allow us to create a new object with the required data, we could have used the default init function, but it will be easier for us to define our own.
Now we will actually have to implement the Animal Object, open up the “Animal.m” file and edit its contents to look like below:


#import "Animal.h"

@implementation Animal
@synthesize name, description, imageURL;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u {
self.name = n;
self.description = d;
self.imageURL = u;
return self;
}
@end


The above code should be pretty easy to read as well, it basically stores the supplied data from the initWithName function and return the object (self).
Now its time to setup the Application delegate to access the database.
Open up the “SQLiteTutorialAppDelegate.h” and edit its contents to look like below:

#import <UIKit/UIKit.h>
#import <sqlite3.h> // Import the SQLite database framework

@interface SQLiteTutorialAppDelegate : NSObject  {

    UIWindow *window;
    UINavigationController *navigationController;

// Database variables
NSString *databaseName;
NSString *databasePath;

// Array to store the animal objects
NSMutableArray *animals;
}

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

@end


What we are doing here is importing the SQLite database framework and creating some variables for storing the database details and an array of animal objects.
Now open up the “SQLiteTutorialAppDelegate.m” file and edit its contents to look like below:


#import "SQLiteTutorialAppDelegate.h"
#import "RootViewController.h"
#import "Animal.h" // Import the animal object header

@implementation SQLiteTutorialAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize animals; // Synthesize the aminals array

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Setup some globals
databaseName = @"AnimalDatabase.sql";

// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];

// Query the database for all animal records and construct the "animals" array
[self readAnimalsFromDatabase];

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

- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}

- (void)dealloc {
[animals release];
[navigationController release];
[window release];
[super dealloc];
}

-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;

// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];

// If the database already exists then return without doing anything
if(success) return;

// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

[fileManager release];
}

-(void) readAnimalsFromDatabase {
// Setup the database object
sqlite3 *database;

// Init the animals Array
animals = [[NSMutableArray alloc] init];

// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from animals";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

// Create a new animal object with the data from the database
Animal *animal = [[Animal alloc] initWithName:aName description:aDescription url:aImageUrl];

// Add the animal object to the animals Array
[animals addObject:animal];

[animal release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

}
sqlite3_close(database);

}

@end


Now I know that may look like a fair bit of code and it probably also looks quite scary! But really it is quite simple and I have tried to comment nearly every line to describe to you what the line does and why it is there.
The checkAndCreateDatabase function checks to see if we have already copied our database from the application bundle to the users filesystem (in their documents folder), if the database hasn’t already been created or it has been removed for some reason it will be recreated from the default database.
Next the readAnimalsFromDatabase function will make a connection to the database that is stored in the users documents folder, and then executes the SQL statement “SELECT * FROM animals”. It will then go through each row that is returned and it will extract the name, description and imageURL from the result and build an Animal object for each. You will see the “sqlite3_column_text” function used here, there are many more of these for returning other field types such as “sqlite3_column_int” for integers, “sqlite3_column_blob” for blobs or “sqlite3_column_value” to get an unknown value.
Now that we have the data in our array and we have it in our known format we are ready to start displaying it.
Open up the “RootViewController.m” file and edit the numberOfRowsInSection to look like the following:


SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
return appDelegate.animals.count;

What this does is it creates a link to the application delegate, and then the second line returns the size f the animals array in out Application delegate, this array was filled previously from the SQLite database.
Now in the cellForRowAtIndexPath function you will need at change it to look like the following:


- (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
    SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];

[cell setText:animal.name];
return cell;
}


We pretty much just added 3 lines under the “// Set up the cell” line, the first one is the same as we added previously to access the application delegate. The second line creates a new Animal object based on the array from the application delegate, it will be used to create a row for each individual record in the database. On the final line we are just setting the text of the cell to the name field from the Animal object.

You can now run the program and you should see a table view with the 4 animals we added to the database, if you added more than my default animals you should see them in here as well.
We will now setup the AnimalViewController, open up the “AnimalViewController.h” file and edit its contents to below:


#import <UIKit/UIKit.h>

@interface AnimalViewController : UIViewController {
IBOutlet UITextView *animalDesciption;
IBOutlet UIImageView *animalImage;
}

@property (nonatomic, retain) IBOutlet UITextView *animalDesciption;
@property (nonatomic, retain) IBOutlet UIImageView *animalImage;

@end


What we are doing above is adding an outlet for the description and image for the Animal, we will use these later on when we link the view up.
Now open up the “AnimalViewController.m” file and add a synthesize call for for the description and image, this will go under the “@implementation AnimalViewController” line, like so:


#import "AnimalViewController.h"

@implementation AnimalViewController

@synthesize animalDesciption, animalImage;


Now it is time to make the detailed view page appear when you select a record. Open up the “AnimalViewController.xib” file from the resources folder and the interface builder should appear.
The first thing we need to do is to set the File’s Owner Class to AnimalViewController, this is done by selecting the “File’s Owner” item in the main window and then clicking Tools > Identity Inspector in the top menu, and then selecting AnimalViewController from the class dropdown.
Your inspector window should now look like this:

We are going to be using a UITextView for the description (as it will allow for word wrapping and scrolling in the case that the description is quite large) and a UIImageView to display the image.


Now that we have everything laid out it is time to link them all up, start by holding control and click+drag from the “File’s Owner” to the “View” objects, a little gray menu will appear and you will need to select view. Now hold control and click+drag from the “File’s Owner” to the UITextView in the layout window, you should see “animalDescription” in the popup list, select it. Repeat this process for the UIImageView and you should see animalImage appear, select it also.
Now save the interface and close the interface builder.
Nearly done! All we have to do now is to setup the code for when a user presses on a record in the table view.
Open up the “RootViewController.h” file and edit its contents to below:


#import <UIKit/UIKit.h>
#import "AnimalViewController.h"

@interface RootViewController : UITableViewController {
AnimalViewController *animalView;
}

@property(nonatomic, retain) AnimalViewController *animalView; 

@end


We are creating an instance of the AnimalViewController to be used bu the RootViewController when a user presses on an item.
Now open up the “RootViewController.m” file and edit the top part of the file to look like below:


#import "RootViewController.h"
#import "SQLiteTutorialAppDelegate.h"
#import "Animal.h"

@implementation RootViewController
@synthesize animalView;

This will just synthesize the animalView that we just added.
First up lets set the default title of our view, to do this you need to uncomment the viewDidLoad function, and edit it to below:


- (void)viewDidLoad {
    [super viewDidLoad];
    // Uncomment the following line to add the Edit button to the navigation bar.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

self.title = @"My Zoo";
}


We also need to edit the didSelectRowAtIndexPath
function in this file, edit it to look like below:


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic -- create and push a new view controller
SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];

if(self.animalView == nil) {
AnimalViewController *viewController = [[AnimalViewController alloc] initWithNibName:@"AnimalViewController" bundle:nil];
self.animalView = viewController;
[viewController release];
}


// Setup the animation
[self.navigationController pushViewController:self.animalView animated:YES];
// Set the title of the view to the animal's name
self.animalView.title = [animal name];
// Set the description field to the animals description
[self.animalView.animalDesciption setText:[animal description]];
// Load the animals image into a NSData boject and then assign it to the UIImageView
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[animal imageURL]]];
UIImage *animalImage = [[UIImage alloc] initWithData:imageData cache:YES];
self.animalView.animalImage.image = animalImage;

}


What we are doing here is checking to see if the animalView object has already been created, if not then create it.
The next few lines are used to setup the animation (slide from right to left) and to set the actual data fields to those of the selected animal.
Now you should be ready to fire up the application and see it in all its glory.
You should see your windows looking like below.



5. Project Files

Here are the source files for this project: Download the project source files

Wednesday, 12 December 2012

NSAttributedString in iOS 6


infoString=@"This is an example of Attributed String";



NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
NSInteger _stringLength=[infoString length];

UIColor *_black=[UIColor blackColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, _stringLength)];



               









UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:3.0] range:NSMakeRange(0, _stringLength)];















UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-3.0] range:NSMakeRange(0, _stringLength)];

















UIColor *_red=[UIColor redColor];
UIColor *_green=[UIColor greenColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_green range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-3.0]range:NSMakeRange(0, _stringLength)];



















UIColor *_green=[UIColor greenColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];

NSShadow *shadowDic=[[NSShadow alloc] init];
[shadowDic setShadowBlurRadius:5.0];
[shadowDic setShadowColor:[UIColor grayColor]];
[shadowDic setShadowOffset:CGSizeMake(0, 3)];
              
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_green range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSShadowAttributeName value:shadowDic range:NSMakeRange(0, _stringLength)];
                



















UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
  [attString addAttribute:NSForegroundColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];              
  [attString addAttribute:NSKernAttributeName value:[NSNumber numberWithInt:5] range:NSMak








UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:2] range:NSMakeRange(0, _stringLength)];








UIColor *_blue=[UIColor blueColor];
UIColor *_blueL=[UIColor colorWithRed:0 green:0 blue:0.5 alpha:0.7];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
                
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_blue range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSBackgroundColorAttributeName value:_blueL range:NSMakeRange(0, 20)];


                





iHope this helped you :)

Wednesday, 25 July 2012

UIAlertView Changes in iOS 5



The UIAlertView class has been available since iOS 2. It is similar to the UIActionSheet class but generally the UIAlertView is used to display an alert message to the user whereas UIActionSheet is useful when you want the user to confirm or choose between a set of options. This post will look at some useful additions to UIAlertView in iOS 5 however that also permit the user to enter some text into the alert view.

The Default Style

Before we look at what has changed in iOS 5 it is probably worth a quick recap of how UIAlertView worked in iOS 4. In all of these examples I will use an alert view with two buttons, a cancel button and an OK button. The code to create and show a basic UIAlertView is as follows:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"DefaultStyle"
                           message:@"the default alert view style"
                           delegate:self
                           cancelButtonTitle:@"Cancel"
                           otherButtonTitles:@"OK", nil]; 
[alertView show];
The initialiser is fairly self-explanatory, it takes a title and a longer description text message which is displayed in the body of the alert view. The delegate is optional and for simple alerts can be set to nil. As I will show in a moment the delegate is required if you want to interact with the alert view for example to find out which button the user pressed.
The cancelButtonTitle may be nil if you do not want a cancel button otherwise it is set to the text to display in the cancel button. Finally there is a nil-terminated list of titles for additional buttons to show in the alert. In this case we just add an OK button. The appearance of the alert view is shown below:
The view is dismissed by pressing either the Cancel or OK buttons. If you want to know which button the user pressed you need to implement some methods from the UIAlertViewDelegate. First we make our view controller adopt the delegate protocol:
@interface UYLViewController : UIViewController <UIAlertViewDelegate>
Then in the view controller we implement alertView:didDismissWithButtonIndex as follows:
- (void)alertView:(UIAlertView *)alertView
        didDismissWithButtonIndex:(NSInteger)buttonIndex
{
  NSLog(@"Alert View dismissed with button at index %d",buttonIndex);
}
The buttonIndex tells us which button was pressed to dismiss the view. The index starts at 0 so in our example with two buttons the Cancel button will give a value of 0 and the OK button will give 1. Of course you will probably want to do something more useful than log the result in a real application.

Plain Text Input

With iOS 5 the UIKit framework has added UIAlertView styles that allow for user input directly into the alert view. This is useful when you need to get a small amount of text input from the user such as a username or password before performing a task. The most simple style is to allow plain text input. The code to create and show a plain text input style alert view is as follows:
UIAlertView *alertView = [[UIAlertView alloc]
                           initWithTitle:@"PlainTextStyle"
                           message:@"Enter plain text"
                           delegate:self
                           cancelButtonTitle:@"Cancel"
                           otherButtonTitles:@"OK", nil];

alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alertView show];
This is similar to creating the default alert view with the exception that we are setting the alertViewStyle property. This property is new in iOS 5 and takes a UIAlertViewStyle to set the style of the alert view. In this case we use UIAlertViewStylePlainTextInput which results in an alert view that looks like this:
The display and dismissal of the keyboard is handled for you to allow the user to enter text into the text field. You can access the text that the user has entered from the delegate we previously used to determine which button was pressed:
UITextField *textField = [alertView textFieldAtIndex:0];
NSLog(@"Plain text input: %@",textField.text);
Note that the text field is accessed via an instance method, textFieldAtIndex, which as the name suggests takes the index of the text field we want. The UIAlertViewStylePlainTextInput alert style contains a single text field at index 0.

Secure Text Input

The plain text input style is obviously not great if the input you want from the user is a password. Typically when entering a password iOS masks characters as they are typed. To get that style of user input we can use the UIAlertViewStyleSecureTextInput:
alertView.alertViewStyle = UIAlertViewStyleSecureTextInput;
The resulting UIAlertView looks the same as the plain text version with the exception that characters are masked a few seconds after they are entered:

Login and Password Input

The final style covers the situation where you want to get both a username and a password in a single alert view. The UIAlertViewStyleLoginAndPasswordInput style gives us an alert view that looks as follows:
The login name field is a plain text field and the password field is a secure text field. In this case we have two text fields that we need to retrieve in the delegate method:
UITextField *loginField = [alertView textFieldAtIndex:0];
NSLog(@"Login input: %@",loginField.text);

UITextField *passwordField = [alertView textFieldAtIndex:1];
NSLog(@"Password input: %@",passwordField.text);

Dynamically enabling/disabling the OK button

One minor refinement we can make when expecting input from the user is to only enable the OK button when the user has actually entered some text. To perform this validation we need to implement an extra delegate method:
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
  UITextField *textField = [alertView textFieldAtIndex:0];
  if ([textField.text length] == 0)
  {
    return NO;
  }
  return YES;
}
The alertViewShouldEnableFirstOtherButton delegate method is called each time the user modifies a text input field in the alert view. It return a BOOL which indicates if the first other button (the OK button in our example) should be enabled or not.
Of course you could do some more sophisticated validation if required but in this case we just check if the user has entered some text into the first text input field. If the text field is empty we return NO which disables the OK button. As soon as the user enters at least one character it is enabled. The Cancel button remains enabled at all times.

Wrapping Up

With iOS 5 the UIAlertView class provides a quick and easy way to get a username or password from the user. There is not much code required to implement these additional alert view styles.

DOWNLOAD CODE HERE.

iHope this helped you...

Monday, 25 June 2012

A Color Chooser for the iPhone



In this blog we’ll show an interesting way to set the background color of a view. We’ll also be looking at different ways to represent the same data, and converting from one representation to another. So, let’s get started!
Start up Xcode, choose Create a new Xcode project, choose the Single View Application template, name the project ColorChooser, and select the options shown here:
Click Next, choose a location to save the project, and then click Create.
Open the MainStoryboard.storyboard file, and drag controls (6 UILabels, 3 UISliders, and 3 UITextFields) to the view. Arrange them thus:
Change the text in the label controls to match the image above. For the sliders, change these values in the Attributes inspector:
Also change the Keyboard value for the three text fields to “Numbers and Punctuation” and the Return Key value to “Done” as shown:
Open the ViewController.h file, and make the changes shown:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UISlider *redSlider;
@property (nonatomic, strong) IBOutlet UISlider *greenSlider;
@property (nonatomic, strong) IBOutlet UISlider *blueSlider;
@property (nonatomic, strong) IBOutlet UITextField *redText;
@property (nonatomic, strong) IBOutlet UITextField *greenText;
@property (nonatomic, strong) IBOutlet UITextField *blueText;
@property (nonatomic, strong) IBOutlet UILabel *hexLabel;
- (IBAction)sliderChanged:(UISlider *)sender;
- (IBAction)textFieldChanged:(UITextField *)sender;
@end
We’ve added properties (as outlets) for the sliders, the text fields, and one of the labels, and also action method headers for the sliders and text fields. Return to the MainStoryboard.storyboard file. Right – click on the View Controller object, and drag from the outlets to their corresponding controls. The redSlider is in the top position, the greenSlider is in the middle, and the blueSlider is at the bottom. Likewise, the redText is at left, the greenText is in the middle, and the blueText is at the right. The hexLabel is the label into which we placed the text #000000 initially.
Finally, change the background color of the main view to black. Don’t worry that this makes the labels’ text invisible, we’ll take care of that in code.
Drag from the sliderChanged action (still in the View Controller’s popup menu) to all three slider controls. In the popup for each, select the Value Changed event. Also drag from the textFieldChanged action to all three text field controls; in their popups, select the Did End On Exit event. When you are finished, the View Controller’s connections should look like this:
Make sure you’ve made all these connections correctly, then open the ViewController.m file. Make the following changes:
#import "ViewController.h"
@interface ViewController ()
- (void) setLabelColorsToContrastWithBackground;
@end
@implementation ViewController
@synthesize redText, redSlider;
@synthesize greenText, greenSlider;
@synthesize blueText, blueSlider;
@synthesize hexLabel;
#pragma mark – private method
- (void) setLabelColorsToContrastWithBackground
{
    CGFloat redValue, greenValue, blueValue, alphaValue;
   
    //set each label’s color to contrast with the background:
    [self.view.backgroundColor getRed:&redValue
                                green:&greenValue
                                 blue:&blueValue
                                alpha:&alphaValue];
   
    for (id subview in self.view.subviews) {
        if ([subview isMemberOfClass:[UILabel class]]) {
            [subview setColor:
             [UIColor colorWithRed:1 - redValue
                             green:1 - greenValue
                              blue:1 - blueValue
                             alpha:1]];
        }
    }
}
#pragma mark – action methods
- (IBAction)sliderChanged:(UISlider *)sender
{
    //set the background color from the sliders:
    self.view.backgroundColor =
        [UIColor colorWithRed:(self.redSlider.value / 255)
                        green:(self.greenSlider.value / 255)
                         blue:(self.blueSlider.value / 255)
                        alpha:1];
    //set the text fields:
    self.redText.text =
        [NSString stringWithFormat:@"%d", (int)self.redSlider.value];
    self.greenText.text =
        [NSString stringWithFormat:@"%d", (int)self.greenSlider.value];
    self.blueText.text =
        [NSString stringWithFormat:@"%d", (int)self.blueSlider.value];
    //set the hexadecimal value in the label using format specifiers:
    self.hexLabel.text =
        [NSString stringWithFormat:@"#%02X%02X%02X",
            (int)self.redSlider.value,
            (int)self.greenSlider.value,
            (int)self.blueSlider.value];
   
    [self setLabelColorsToContrastWithBackground];
}
- (IBAction)textFieldChanged:(UITextField *)sender
{
    //set the sliders from the integer values of the texts:
    self.redSlider.value = [self.redText.text intValue];
    self.greenSlider.value = [self.greenText.text intValue];
    self.blueSlider.value = [self.blueText.text intValue];
   
    //set the background color from the sliders:
    self.view.backgroundColor =
    [UIColor colorWithRed:(self.redSlider.value / 255)
                    green:(self.greenSlider.value / 255)
                     blue:(self.blueSlider.value / 255)
                    alpha:1];
   
    //set the hex value in the label using format specifiers:
    self.hexLabel.text =
        [NSString stringWithFormat:@"#%02X%02X%02X",
            (int)self.redSlider.value,
            (int)self.greenSlider.value,
            (int)self.blueSlider.value];
   
    [self setLabelColorsToContrastWithBackground];
}
#pragma mark – View Controller delegate methods:
- (void)viewDidLoad
{
    [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    [self setLabelColorsToContrastWithBackground];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
   
    //we can do this type of chained C assignment as long as
  //the types are the same:
    self.redText = self.blueText = self.greenText = nil;
  self.redSlider = self.blueSlider = self.greenSlider = nil;
  self.hexLabel = nil;
}
…
In a .m file, the @interface / @end section encloses what is known as a class extension in Objective – C. In a class extension, we can place any properties or methods that we don’t want to be public members of the class. (All properties and methods in the .h file are public, meaning that they are visible to any classes that instantiate the class.) Here, we declare a private method called setLabelColorsToContrastWithBackground.
Next, we @synthesize all of the properties we declared in the .h file. Note that we can synthesize more than one property on a line. Often it makes sense to group these logically, as we’ve done here.
After synthesizing the properties, we implement the private method we just declared. This method sets the labels’ colors to contrast with the color of the view’s background. It does this by obtaining the red, green, and blue values of the current background color, then setting each label’s color to these values subtracted from 1. Note the use of fast enumeration (the for in loop) to get all the subviews of the main view. We determine if the subview is a label before attempting to set it’s color, for two reasons: first, not all controls may have a setColor method, and second, we really don’t want to set the color of anything but a label. This way of doing things avoids setting the color of six labels individually.
Next we define the sliderChanged: method. First we set the background color according to the values of the sliders. But we have to convert between the 0..255 range of the slider to the 0..1 range expected by the RGBA components of the UIColor structure. This is done by dividing each slider’s value by 255 before passing it to the colorWithRed: Green: Blue: Alpha: method.
We then set the text fields to an integer representation of each slider’s value. Slider controls actually post their values as floats, not integers; this necessitates that we cast each value to an int before sending it to the format specifier %d.
Finally, we build the hexadecimal string for display in the hexLabel by using the format string
@”#%02X%02X%02X” with each slider’s int value. This will print a #, followed by a hexadecimal representation of the int value passed in. The 0 indicates that the digit will be left padded by zero’s within it’s field width, and the 2 indicates the field width. As the last step, we call the setLabelColorsToContrastWithBackground method.
The textFieldChanged: method works in a very similar way to the sliderChanged: method, we’ll leave it up to you to analyze it.
In viewDidLoad, we simply make sure that the labels contrast with the black background we initially set on the view. In viewDidUnload, we set all the subviews of the main view to nil to ensure that the reference counter releases these objects.
Run the ColorChooser, and have fun experimenting with the interface!