Saturday, March 19, 2011

A Simple UITableView tutorial

In this tutorial we will learn how to implement a list view called UITableView on iOS and also how to add your own custom cell to it to give it a whole new look unlike default table view provided by iOS.
The best part is that we'll make this table in our on view based application and not using any of the templates provided by iOS.

So Lets get started!

Step1- Open Xcode and on the left choose iphone application>view based application.Lets name it as UITableViewSampleViewController click next.
Now open UITableViewSampleViewControllerViewController.xib and add a UITableView to your main view and your nib will look as follows......

Step 2- Now go to your UITableViewSampleViewControllerViewController.h file and now you need to declare a IBOutlet of your table view in your .h file.so replace your
UITableViewSampleViewControllerViewController.h file with the following code snippet.


#import <UIKit/UIKit.h>

@interface UITableViewSampleViewControllerViewController : UIViewController {
    IBOutlet UITableView *sampleTableView;
}
@property(nonatomic, retain) IBOutlet UITableView *sampleTableView;

@end

and synthesize this property in your .m file of the same by writing the following statement in your .m file just below @implementation

@synthesize sampleTableView

what we did here is tell our view in xib that hey there is a IBOutlet of the table view in your controller file and @synthesize automatically generates getter and setter for the same.

Step 3-The next step is to link the outlet we just created with the table view which we had put in our xib file. So now open  UITableViewSampleViewControllerViewController.xib and link the table view to the outlet in file owner as follows-


and delegate and datasource as follows--


Thats all in the nib.

Step 4 - Now lets implement the delgates of our table view in our view controller files.
Now we linked the delegate and datasource of our table view to our file owner but we need to tell our view controller that he's gonna implement these delegates by adding the following bold statements in our .h file first.
#import <UIKit/UIKit.h>

@interface UITableViewSampleViewControllerViewController : UIViewController <UITableViewDelegate,UITableViewDataSource> {
    IBOutlet UITableView *sampleTableView;
}
@property(nonatomic, retain) IBOutlet UITableView *sampleTableView;

@end

Now we need to implement the delegate methods for our sampleTableView in our .m file.Delegate methods define the properties of the object which they are related to. By properties  I mean the whole functionality.
Just compile your code before proceeding forward.And if you get any errors then please go through again you might have missed out something.

So now add the following 4 delegate methods in your UITableViewSampleViewControllerViewController.m file any where between @implementation and @end. For now we'll have 1 section and 20 rows in our sampleTableView.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 20;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"row %i",[indexPath row]];
    // Configure the cell...
   
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  
}

Just Build and Run your code and you should see something like this.



Step 5 -For that we need to add a new file. right click on the classes folder and select Add New File option Select objective c class and UITableViewCell . Click next name it as SampleTableViewCell.m and make sure that also generate .h is checked. click choose and two new files will be created in you classes folder.


Also add a xib file of this cell same right click on your resource folder and add a new empty xib file and name it as same as your table cell file.In this case as SampleTableViewCell.check iphone.


Now open SampleTableViewCell.xib and add a UITableViewCell from library to your empty xib it should look as follows.


Now to this label add a UIView from your library, a label and a ImageView and your cell will look something like - and make sure that the view dimensions and the table cell dimensions and x y are same. alos resixe image view and label according to your requirement.


Also Make sure that class which your this tableviewcell is extending is SampleTableViewCell just open the inspector and change the class as follows.





Step 6 - Now lets go and make outlets for these imageview,label and view that we added to our xib in our SampleTableViewCell.h. Add replace the code in your SampleTableViewCell.h with the following

#import <UIKit/UIKit.h>


@interface SampleTableViewCell : UITableViewCell {
    IBOutlet UIView *cellBackgroundView;
    IBOutlet UILabel *titleLabel;
    IBOutlet UIImageView *cellImage;
}
@property(nonatomic, retain) IBOutlet UIView *cellBackgroundView;
@property(nonatomic, retain) IBOutlet UILabel *titleLabel;
@property(nonatomic, retain) IBOutlet UIImageView *cellImage;
@end

and synthesize the same in your .m file by adding this line below @implementation
@synthesize cellBackgroundView,titleLabel,cellImage;

Step 7 - Next is the linking process of these outlets in our xib. Open your SampleTableViewCell.xib and link the outlets as follows. Be careful that now you dont have to connect your outlets to your FileOwner but to your tableView cell because it is only extending your SampleTableViewCell class.






Step 8 - Phew!!Now our cell is up and ready to be included in our table cell.Just go to UITableViewSampleViewController.m file and replace the code in cellForRowAtIndexPath method with the following code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";   
    SampleTableViewCell *cell=(SampleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if(cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"SampleTableViewCell" owner:self options:nil];
        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[SampleTableViewCell class]])
                cell=(SampleTableViewCell *)oneObject;
    }
   
    // Configure the cell...
    cell.titleLabel.text = [NSString stringWithFormat:@"row %i",[indexPath row]];
    cell.cellImage.image = [UIImage imageNamed:@"normal.jpg"];
    cell.cellBackgroundView.backgroundColor = [UIColor grayColor];
    return cell;
}
make sure that you import SampleTableViewCell.h file in this file. and for imageview you need to add a image to your resource folder just drag and drop any image and check copy items into destination folder box so that that image is automatically added to your project folder.
Note: Just open your Tableview controller xib and make the row height same as your table cell. otherwise your cells will overlap each other.
Thats all we're done The final output should look as follows .. in our next tutorial we'll learn how to perform an action on selection of a row in this tableview.


Ok goodbye Happy Coding!!!!





















Tuesday, January 4, 2011

Writing a simple action on button press.

Hi guys,
In this tutorial we will learn how to add buttons to your application and associating actions to your buttons. This tutorial is mainly intended for no offence :P.

Step1- Open your xcode->View based application, name it something like ButtonDemo.Save.

Step2- Ok now lets design the UI first. On the left hand side of xcode there is a folder called Resources.
Go to Resources.Double click on the file ButtonDemoViewController.xib. Sometimes this is called as nib file.This will open your Interface builder which is a tool provided by apple for User Interface design.




                                                                             Fig-1.0
Step3- Now apple provides you with its default tool set or library from where you can simply drag and drop the buttons,labels etc. UI elements onto your interface builder. So now on top toolbar of interface builder click on tools->Library it will open up the apple library for designing your app(right side of fig 1.0). In this there will be Rounded Rect button and a label. Now in your main window where a list of items is there like File Owner etc(left side of fig 1.0). There is a View. Double click on the view ,this opens a window which shows your current view(middle of fig 1.0). Drag and drop one button and a label onto this and final UI looks something like Fig-1.0 and do remember to save everything in interface builder before closing the main window.

Step4- Ok now time to write some code. Now open your ButtonDemoViewController.h file and paste the following code into your .h file. The .h file contains the declarations of variables and methods which you will implement in the respective .m file. It should look something like this.

#import <UIKit/UIKit.h>

@interface ButtonDemoViewController : UIViewController {

}
-(IBAction)sampleButtonPressed;
@end
Here what we did is declared an action named sampleButtonPressed.
Save the project Command+S.

Step5- Now time to tell the button to perform an action on press of it. In technical term how to create a link between the code and the interface builder(your view). Don't be scared!!!
                                                                                Fig-2.0
Open your IB(Interface Builder) Ctrl+click on File Owner located in your main window. And a drop down will open (as shown in fig 2.0). In this there will be your function named sampleButtonPressed in Received Actions inside this drop down. Now click on the circle next to it and drag and drop it on the button in your view as shown in figure 2.0. Now your button knows that there is a method named
sampleButtonPressed in your ButtonDemoViewController class. This completes the link between
your code and the interface builder. One more thing do remember to save the changes to the interface
builder before any confusion pops up.

Step6-Now lets tell our xcode to do an action on press of this button. Go to ButtonDemoViewController.m where the action should be implemented. Copy and paste the following code to your ButtonDemoViewController.m file.
Now what we need to do is on button press the text in the label should change.
We have placed the label in our IB but not connected it to our .m class which is also referred to as the
controller class of its nib in the resources folder. So declare a label in our ButtonDemoViewController.h file.
Now copy paste the following code in your ButtonDemoViewController.h file:
#import <UIKit/UIKit.h>

@interface ButtonDemoViewController : UIViewController {
    UILabel *msgLbl;
   
}
@property(nonatomic,retain) IBOutlet UILabel *msglbl;
-(IBAction)sampleButtonPressed;
@end
Only modification we did here is declared a UILabel called msgLbl. Open the nib file
in the interface builder and Ctrl+click on the file owner there click hold on the msgLbl , drag and drop on the label in your view as shown in Fig 3.0.



                                                                              Fig-3.0
What this did is enables you to access this label by the name of msgLbl in your code.

Step6- Now its time to implement our action in our ButtonDemoViewController.m file

Now add the following line at the top of .m file just below @implementation.

@synthesize msgLbl;
What this does is generates the getter and setter for the property declared in the .h file.

Now copy and paste the function mentioned below in your .m file just above the viewDidUnload method.


-(IBAction)sampleButtonPressed{
    msgLbl.text = @"Hello";//change the text of label on press of button and change it to hello.
}
Thats all! Save the application Command+S.
Command+B to build.
And finally run Command+R to run it.
If you have systematically followed the procedure above the final screens look like below.




After click........






Hurray!!!!!

Monday, January 3, 2011

How to fetch a you tube video on iphone or ipad.

Create a view base application and add a webView on it and call this html string to get the video of the desired url of youtube you want........
you can use this part of code .....

    NSString *embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
    background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";
    NSString *html = [NSString stringWithFormat:embedHTML, urlString];
    UIWebView *videoWebView = [[UIWebView alloc] initWithFrame:frame];
    [videoView loadHTMLString:html baseURL:nil];
   //here u can add this to your own calayer or on any view you want.....   
    [videoWebView release];

Post your queries on iphone app design and development