How to Set Subtitle on Tableview Cell in iPhone

Introduction

In this article I will create a Single View application. Here I will add a table view using outlet and connect it's delegate and datasource to the file owner. To set a subtitle on a table view cell we write code for tableViewcellForRowAtIndexPath (the table view's delegate method).

To better understand it we use the following procedure.

Step 1

Open XCode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now Select Single View Application and click on "Next".

Step 4

Now provide your Product Name and Company Identifier. 

Step 5

Select the location where you want to save your project and click on "Create".

Step 6

Now we write the code of the Objective-C classes:

TableExampleViewController.h

//
// TableExampleViewController.h
// TableColor
//
// Created by Sachin Bhardwaj on 24/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import <UIKit/UIKit.h>
@interface TableExampleViewController : UIViewController<UITableViewDelegateUITableViewDataSource>
@property (nonatomicretainNSArray *colorNames;
@property(strong,nonatomic)IBOutlet UITableView *table;
@end

TableExampleViewController.m

//
// TableExampleViewController.m
// TableColor
//
// Created by Sachin Bhardwaj on 24/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import "TableExampleViewController.h"
@interface TableExampleViewController ()
@end
@implementation TableExampleViewController
@synthesize colorNames,table;
- (void)viewDidLoad
{
[super viewDidLoad];
[[self table] setBackgroundColor:[UIColor yellowColor]];
self.colorNames = [[NSArray alloc]initWithObjects:@"iPhone"@"iPad",@"iPod"@"Mac"@"Mac mini"nil];
}
- (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section {
return [self.colorNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
UIImage *cellImage = [UIImage imageNamed:@"apple.png"];
cell.imageView.image = cellImage;
NSString *colorString = [self.colorNames
objectAtIndex: [indexPath row]];
cell.textLabel.text = colorString;
NSString *subtitle = @"All about the color ";
subtitle = [subtitle stringByAppendingString:colorString];
cell.detailTextLabel.text = subtitle;
return cell;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

Step 7

Click on the run button to show the output.

Output in iPhone:

Output-in-iPhone.png


Similar Articles