Showing posts with label uitableview tutorial. Show all posts
Showing posts with label uitableview tutorial. Show all posts

Tuesday, April 9, 2013

Adding/Deleting Rows Dynamically (UITableView)

To answer Mr. Ramanan R Rengaraj's question "How to add an add and delete button in nav bar to insert / delete rows dynamically."

Prerequisite:
1. UITableView (http://iosmadesimple.blogspot.com/2012/10/adding-uitableview-tutorial.html)
2. UINavigationController (http://iosmadesimple.blogspot.com/2012/08/navigation-based-project-doing-it.html)

This tutorial will be based mainly from the UITableView tutorial, I'm only going to tweak it a little so we can add and delete rows dynamically.

Let's start!

1. Create a new Xcode Project, and choose a Single View Application template. After creating a Single View Application Project, you will see that there is an AppDelegate and a ViewController class. We will not be using the ViewController class, you may choose to delete it from your project.



2. Create a New File, Objective-C class, subclass of UITableViewController. In my case, I named it MyTableViewController.

3. Click MyTableViewController.xib file, select the tableview.  Choose the "Grouped" Style under Table View. 
//You may choose to change the View size from Retina 4 Full Screen to Retina 3.5 Full Screen under Simulated Metrics.

Grouped Style Table View allows us to see the adding and deleting of rows dynamically.

4. Select the AppDelegate.h file, import MyTableViewController class. Add a MyTableViewController property and a UINavigationController property. Synthesize these properties in your AppDelegate.m file.

@property (strong, nonatomic) MyTableViewController *viewController;
@property (strongnonatomicUINavigationController *navController;

5. Go to AppDelegate.m file, under ApplicationDidFinishLaunchingWithOptions method, create and initialize your viewController property. Next, create and initialize your navController such that your navController's rootViewController is your viewController variable. Set window's rootViewController with your navController.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    self.viewController = [[MyTableViewController alloc] initWithNibName:@"MyTableViewController" bundle:nil];
    self.navController = [[UINavigationController alloc] initWithRootViewController:self. viewController];
    self.window.rootViewControllerself.navController;
    [self.window makeKeyAndVisible];
    return YES;
}


6. Go to MyTableViewController.m file. Create an array variable (NSMutableArray) for the list of items we want to show in our tableView. I also have an int variable which will be useful for this tutorial.
NSMutableArray *items;
int num;


7. Under viewDidLoad of MyTableViewController, we will set the title and the items in our array, set the num of our int variable and create the two navigation buttons for add and delete.

 // Set Title
self.title = @"Items";

// Set initial values in our array
items = [[NSMutableArray allocinitWithObjects:@"Item No. 1"@"Item No. 2"@"Item No. 3"@"Item No. 4"@"Item No. 5"@"Item No. 6"nil];


// Set int variable, since our last item number is six, we will also set this int variable to six.
num = 6;

// create the two navigation buttons
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Add"
                                   style:UIBarButtonItemStyleBordered
                                   target: self
                                   action:@selector(addItemToArray)];
    self.navigationItem.rightBarButtonItemaddButton;
    
    UIBarButtonItem *delButton = [[UIBarButtonItem alloc]
                                  initWithTitle:@"Del"
                                  style: UIBarButtonItemStyleBordered
                                  target: self
                                  action:@selector(delItemToArray)];
    self.navigationItem.leftBarButtonItem delButton;


8. Implement the addItemToArray and delItemToArray methods in our MyTableViewController class.
//Add Item To Array
- (void)addItemToArray {
    num++;
    [items addObject:[NSString stringWithFormat:@"Item No. %d", num];
    [self.tableView reloadData];
}


//Delete Item To Array
- (void)delItemToArray {
    num--;
    [items removeLastObject];
    [self.tableView reloadData];
}

9. Lastly, let's update the codes in our TableView Data Source methods. 
//The codes in our Data Source methods are just the same with the codes on our previous UITableView tutorial.
#pragma mark - Table view data source
- (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.
    // Usually the number of items in your array (the one that holds your list)
    return [items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //Where we configure the cell in each row

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell;
    
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell allocinitWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // Configure the cell... setting the text of our cell's label
    cell.textLabel.text = [items objectAtIndex:indexPath.row];
    return cell;
}





10. Done! Hit Run!

//At first run, we'll see the initial values in our array.

//Hit Add button.


//Hit Delete Button.

Download Project Code 

Tuesday, October 23, 2012

Adding a UITableView Tutorial

For beginners, this is one of the difficult views to learn, anyhow let's learn how to add a tableview in our view.
A tableView is used to show a list of objects.

Adding a TableView Using Interface Builder

1. Prepare the superview of your tableView. (Superview is the view where we would like to put our tableview.) In our example, the UIViewController's view is going to be our tableView's superview.

2. Drag a tableView UI to our View.
If you hit run, you will see your tableView on your screen. You can scroll it up and down.

3. Set the tableview datasource and delegate in your Interface file.

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>


4. Add an IBOutlet tableview property and synthesize it.

@property (nonatomic, strong) IBOutlet UITableView *sampleTableView
@synthesize sampleTableView; //.m file below @implementation ViewController

5. Connect your IBOutlet to our tableView in your xib file.



6. Create an array that will hold your list for you. If your items are static (will not change), use NSArray, else, if somewhere in your program, you need to change your array, use NSMutableArray.

@property (nonatomicstrong) NSArray *items;

7. In your viewDidLoad function, allocate and initialize your array with your objects. Currently, let's use simple string objects, NSString.
items = [[NSArray alloc] initWithObjects:@"Item No. 1"@"Item No. 2"@"Item No. 3"@"Item No. 4"@"Item No. 5"@"Item No. 6", nil];

8. Set our sampleTableView's datasource and delegate to its File's Owner.



9. Lastly, implement the UITableView Datasource and Delegate methods. These are necessary to manipulate our tableView.


#pragma mark - Table view data source
- (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.
    // Usually the number of items in your array (the one that holds your list)
    return [items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //Where we configure the cell in each row

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell;
    
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // Configure the cell... setting the text of our cell's label
    cell.textLabel.text = [items objectAtIndex:indexPath.row];
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    // If you want to push another view upon tapping one of the cells on your table.

    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}


10. Hit Run!


Adding a TableView Programmatically

1. From the steps we had above, delete the tableView UI in our xib file, and delete the IBOutlet from our tableView property.

@property (nonatomicstrongIBOutlet UITableView *sampleTableView

2. On your viewDidLoad function (of your ViewController.m file). Follow the commented steps.

- (void)viewDidLoad {
    [super viewDidLoad];
    //Create a tableView programmatically
    self.sampleTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.yself.view.frame.size.widthself.view.frame.size.height 2) style:UITableViewStylePlain];
    //Add the tableview as sa subview of our view ---> making "view" our superview.
    [self.view addSubview:sampleTableView];
    //From step 7 above.
    items = [[NSArray allocinitWithObjects:@"Item No. 1"@"Item No. 2"@"Item No. 3"@"Item No. 4"@"Item No. 5"@"Item No. 6"nil];
    //From the step 8 above, this is how we do that programmatically
    self.sampleTableView.delegateself;
    self.sampleTableView.dataSourceself;
}

3. Done! When you hit run, you'll see the same result.




Blocks From one Class to Another

One popular scenario in using blocks is when you need to update your view after a web service call is finished.