Friday, April 5, 2013

How to create and display a "list" of items (using Table View)

Creating a simple Table View

  1. Open the storyboard, from the right panel, drag a Table View control onto the story board.
  2. Open ViewController.h and add the highlighted text:

    @interface
     XViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

    @end
  3. Open ViewController.m and insert the following line in between the @implementation section:

    NSArray
    *tableData;
  4. Add the following code in the viewDidLoad function:
    tableData
     = [NSArray arrayWithObjects:@"Item 1"@"Item 2"@"Item 3"@"Item4"nil];
  5. Add the following 2 functions as well:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [tableData count];
    }


    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *simpleTableIdentifier = @"SimpleTableItem";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
        }
        
        cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
        return cell;
    }
  6. Open storyboard
  7. Right click drag from the TableView control to the yellow icon and release. Choose dataSource.


  8. Done. Run the app:


Adding an icon next to each list item

  1. Click the menu item, File > Add files to "your project".
  2. Choose a file for the icon: 
  3. In the ViewController.m file, in the function cellForRowAtIndexPath, paste the following line at the indicated location:


        cell.imageView.image = [UIImage imageNamed:@"AddedImage.jpg"];

  4. Run the project.

No comments:

Post a Comment