Problem adding UITableViewCell manually - iphone

I am trying to add a UITableViewCell at the very bottom of my UITableView programatically. I am getting an index out of bounds error, which I am not sure how to resolve:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [items count]+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
if (indexPath.row == [items count] + 1) {
UITableViewCell* cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MoreCell"] autorelease];
cell.textLabel.text = #"More...";
return cell;
}
else {
STUser *mySTUser;
mySTUser = [items objectAtIndex:indexPath.row]; //!!INDEX OUT OF BOUNDS HERE!!
AsyncImageView* asyncImage = nil;
UILabel* loginLabel = nil;
UILabel* fullNameLabel = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
CGRect frame = CGRectMake(0, 0, 44, 44);
CGRect loginLabelFrame = CGRectMake(60, 0, 200, 10);
CGRect fullNameLabelFrame = CGRectMake(60, 20, 200, 10);
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
asyncImage = [[[AsyncImageView alloc]initWithFrame:frame] autorelease];
[cell.contentView addSubview:asyncImage];
loginLabel = [[[UILabel alloc] initWithFrame:loginLabelFrame] autorelease];
[cell.contentView addSubview:loginLabel];
fullNameLabel = [[[UILabel alloc] initWithFrame:fullNameLabelFrame] autorelease];
[cell.contentView addSubview:fullNameLabel];
asyncImage.tag = IMAGE_TAG;
loginLabel.tag = LOGIN_TAG;
fullNameLabel.tag = FULL_NAME_TAG;
}
else {
asyncImage = (AsyncImageView *) [cell.contentView viewWithTag:IMAGE_TAG];
loginLabel = (UILabel *) [cell.contentView viewWithTag:LOGIN_TAG];
fullNameLabel = (UILabel *) [cell.contentView viewWithTag:FULL_NAME_TAG];
}
// Configure the cell...
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
CGRect frame = CGRectMake(0, 0, 44, 44);
asyncImage = [[[AsyncImageView alloc]initWithFrame:frame] autorelease];
NSURL* url = [NSURL URLWithString:mySTUser.avatar_url_large];
[asyncImage loadImageFromURL:url];
asyncImage.tag = IMAGE_TAG;
[cell.contentView addSubview:asyncImage];
CALayer * l = [asyncImage layer];
[l setMasksToBounds:YES];
[l setCornerRadius:5.0];
CGRect loginLabelFrame = CGRectMake(60, 0, 200, 20);
loginLabel = [[[UILabel alloc] initWithFrame:loginLabelFrame] autorelease];
loginLabel.text = [NSString stringWithFormat:#"%#",mySTUser.login];
loginLabel.tag = LOGIN_TAG;
[cell.contentView addSubview:loginLabel];
CGRect fullNameLabelFrame = CGRectMake(60, 20, 200, 20);
fullNameLabel = [[[UILabel alloc] initWithFrame:fullNameLabelFrame] autorelease];
fullNameLabel.text = [NSString stringWithFormat:#"%# %#",mySTUser.first_name, mySTUser.last_name];
fullNameLabel.tag = FULL_NAME_TAG;
fullNameLabel.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
[cell.contentView addSubview:fullNameLabel];
return cell;
}
}
If the count is items + 1 I want to return the More Cell, if not, then I want it to create all of the other cells. Not sure why I get the index out of bounds since the code should never reach that point.

indexPath.row is zero based.
Change:
if (indexPath.row == [items count] + 1) {
To:
if (indexPath.row == [items count]) {

Arrays in Objective-C and almost all other programming languages are zero-based. That means the first object has index 0, and the last object has index (length - 1).
Therefore, the condition
if (indexPath.row == [items count] + 1) {
should be changed to
if (indexPath.row == [items count]) {

Related

Load more at the top of uitableview

I need a load more cell at the top of my table populated with custom cell, the first time that I populate the table is all ok, no overlap and no problem, if I try to load more cell this cell appear but with the wrong height and if I try to scroll the cell change position randomly!
This is my code, where the mistake for you?
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.arrayMessaggi count] + 1;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (indexPath.row == 0) {
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *labelLoad = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[labelLoad setBackgroundColor:[UIColor clearColor]];
[labelLoad setTextAlignment:NSTextAlignmentCenter];
[labelLoad setText:[NSString stringWithFormat:#"%d - Load more...",indexPath.row]];
[labelLoad setText:#"Load more..."];
[labelLoad setTag:3];
[cell.contentView addSubview:labelLoad];
}
UILabel *labelLoad = (UILabel *)[cell.contentView viewWithTag:3];
[labelLoad setText:[NSString stringWithFormat:#"%d - Load more...",indexPath.row]];
}
else {
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
PFObject *obj = [self.arrayMessaggi objectAtIndex:indexPath.row - 1];
PFUser *user = [obj objectForKey:#"daUtente"];
float height = [self getStringHeight:[obj objectForKey:#"TestoMessaggio"] andFont:[UIFont systemFontOfSize:13]];
UILabel *labelUser = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 280, 20)];
[labelUser setBackgroundColor:[UIColor clearColor]];
[labelUser setText:[user objectForKey:#"username"]];
[labelUser setFont:[UIFont systemFontOfSize:13]];
[labelUser setTag:1];
[cell.contentView addSubview:labelUser];
}
PFObject *obj = [self.arrayMessaggi objectAtIndex:indexPath.row - 1];
PFUser *user = [obj objectForKey:#"daUtente"];
UILabel *labelUser = (UILabel *)[cell.contentView viewWithTag:1];
[labelUser setText:[NSString stringWithFormat:#"%d - %#",indexPath.row,[user objectForKey:#"username"]]];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
float height = 44;
if (indexPath.row > 0) {
PFObject *obj = [self.arrayMessaggi objectAtIndex:indexPath.row - 1];
NSString *text = [obj objectForKey:#"TestoMessaggio"];
height = 30 + [self getStringHeight:text andFont:[UIFont systemFontOfSize:13]] + 10;
}
return height;
}
- (void) setPullDownToRefresh {
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(aggiornaTabella:) forControlEvents:UIControlEventValueChanged];
[self.messagesTableView addSubview:refreshControl];
}
- (void) aggiornaTabella:(UIRefreshControl *)myRefreshControl {
self.arrayMessaggi = [NSMutableArray arrayWithArray:objects];
self.messagesTableView = [[UITableView alloc] init];
[self.messagesTableView reload data];
}

UITableViewCell row disorder

I posted some question with same source code before. I just found out some other strange thing.The thing is that If I define reuse cell identifier, each row color is weird.
But If I don't use reuse identifier, its working.
Please give me any tips why each row color does not keep the order.
//its working
static NSString *CellIdentifier = #"Cell";
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"] autorelease]
cell.contentView.backgroundColor = (indexPath.row %2) ? [UIColor redColor] : [UIColor yellowColor];
//it does not work.
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; -- does not working.
cell.contentView.backgroundColor = (indexPath.row %2) ? [UIColor redColor] : [UIColor yellowColor];
- (void)viewDidLoad {
[super viewDidLoad];
//Initialize the array.
listOfItems = [[NSMutableArray alloc] init];
//Add items
[listOfItems addObject:#"1"];
[listOfItems addObject:#"2"];
[listOfItems addObject:#"3"];
[listOfItems addObject:#"4"];
[listOfItems addObject:#"5"];
[listOfItems addObject:#"6"];
[listOfItems addObject:#"7"];
[listOfItems addObject:#"8"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listOfItems count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *aLabel; UILabel *bLabel; UILabel *v1Label; UILabel *v2Label;; UIView *v1; UIView *v2;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog(#" cell null");
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.contentView.backgroundColor = (indexPath.row %2) ? [UIColor redColor] : [UIColor yellowColor];
aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(9.0, 8.0, 50.0, 20.0)] autorelease];
aLabel.tag = 1;
aLabel.font = [UIFont systemFontOfSize:30];
[cell.contentView addSubview:aLabel];
v1 = [[UIView alloc] initWithFrame:CGRectMake(0, 44, 320, 116)];
v1.backgroundColor = [UIColor whiteColor];
v1.tag = 10;
v1.hidden = YES;
[cell.contentView addSubview:v1];
[v1 release];
UILabel *a = [[[UILabel alloc] initWithFrame:CGRectMake(0, 10, 100, 100)] autorelease];
a.text = #"v1.test1";
[v1 addSubview:a];
UILabel *b = [[[UILabel alloc] initWithFrame:CGRectMake(0, 40, 100, 100)] autorelease];
b.text = #"v1.test2";
[v1 addSubview:b];
v2 = [[UIView alloc] initWithFrame:CGRectMake(0, 44, 320, 100)];
v2.backgroundColor = [UIColor blueColor];
v2.tag = 11;
v2.hidden = YES;
[cell.contentView addSubview:v2];
[v2 release];
UILabel *c = [[[UILabel alloc] initWithFrame:CGRectMake(0, 10, 100, 100)] autorelease];
c.text = #"v2.test1";
[v2 addSubview:c];
UILabel *d = [[[UILabel alloc] initWithFrame:CGRectMake(0, 40, 100, 100)] autorelease];
d.text = #"v2.test2";
[v2 addSubview:d];
}
else {
aLabel = (UILabel *)[cell.contentView viewWithTag:1];
//
v1 = (UIView *) [cell.contentView viewWithTag:10];
v2 = (UIView *) [cell.contentView viewWithTag:11];
}
aLabel.text = [listOfItems objectAtIndex:indexPath.row];
if (SelectedIndexPath == indexPath.row)
{
if ([aLabel.text intValue] % 2) {
v1.hidden = NO;
v2.hidden = YES;
}
else {
v1.hidden = YES;
v2.hidden = NO;
}
}
else {
v1.hidden = YES;
v2.hidden = YES;
}
return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (SelectedIndexPath == indexPath.row)
{
return 162.0;
}
else {
return 46.0;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (SelectedIndexPath == -1)
{
OldSelectedIndexPath = indexPath.row;
SelectedIndexPath = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:NO];
}
else
{
if (SelectedIndexPath == indexPath.row)
{
OldSelectedIndexPath = SelectedIndexPath;
SelectedIndexPath = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:NO];
}
else
{
SelectedIndexPath = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:OldSelectedIndexPath inSection:indexPath.section], indexPath, nil] withRowAnimation:NO];
OldSelectedIndexPath = SelectedIndexPath;
}
}
}
Move the coloring code outside of the if (cell == nil) { block. Just because a cell was created for an even-numbered index doesn't mean it will only be reused for even ones.
Here's a simple example of code for coloring cells that are being reused:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = #"Anything";
cell.contentView.backgroundColor = (indexPath.row %2) ? [UIColor redColor] : [UIColor yellowColor];
return cell;
}

UILabel overlapping in UITableViewCell

I have a 2x UILabels, 1 title 1 subtitle,
Which are meant to change when a segmentedControl is selected.
It works but instead i get the SAME UILabel overlapping itself when a different segment is selected?
I think i need to create an action to remove the label from the superview before it is redisplayed onto the cell? just wondering how to go about it
- (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];
}
EventUpcoming *aEventUpcoming = [euEvent objectAtIndex:indexPath.section];
EventWeekly *aEventWeekly = [ewEvent objectAtIndex:indexPath.section];
UILabel *cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 290, 20)];
UILabel *cellSubtitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 290, 20)];
NSString *titleString = [[NSString alloc] init];
NSString *subtitleString = [[NSString alloc] init];
if (segmentedControl.selectedSegmentIndex == 0)
{
Event *aEvent = [aEventUpcoming.event objectAtIndex:indexPath.row];
titleString = aEvent.name;
subtitleString = aEvent.subtitle;
}
else
{
Event *aEvent = [aEventWeekly.event objectAtIndex:indexPath.row];
titleString = aEvent.name;
subtitleString = aEvent.subtitle;
}
NSString *titleStringUC = [titleString uppercaseString];
NSString *subtitleStringLC = [subtitleString lowercaseString];
cellTitle.text = titleStringUC;
cellTitle.font = [UIFont boldSystemFontOfSize:11];
cellTitle.textColor = [UIColor colorWithRed:142/255.0f green:142/255.0f blue:142/255.0f alpha:1];
cellTitle.shadowColor = [UIColor whiteColor];
cellTitle.shadowOffset = CGSizeMake(1, 1);
cellTitle.backgroundColor = [UIColor clearColor];
cellSubtitle.text = subtitleStringLC;
cellSubtitle.font = [UIFont boldSystemFontOfSize:11];
cellSubtitle.textColor = [UIColor colorWithRed:177/255.0f green:177/255.0f blue:177/255.0f alpha:1];
cellSubtitle.shadowColor = [UIColor whiteColor];
cellSubtitle.shadowOffset = CGSizeMake(1, 1);
cellSubtitle.backgroundColor = [UIColor clearColor];
tableViewCellSeparator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"TableCellSeparator.png"]];
tableViewCellSeparator.frame = CGRectMake(0, cell.bounds.size.height - 2, 320, 2);
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[cell.contentView addSubview:cellTitle];
[cell.contentView addSubview:cellSubtitle];
[cell.contentView addSubview:tableViewCellSeparator];
return cell;
}
UPDATE:
Both were very valid answers, tyvm
You're not reusing your cell correctly, so you're not getting the performance benefit of reuse, and making the code more complicated. You're also not using the pieces that Apple gives you to work with out of the box.
First, you should create and add all your subviews inside the cell==nil block. This is where you create your reusable cell. In the rest of the routine, you're just reconfiguring the cell. This is much, much faster.
Second, UITableViewCell already has two labels built-in. You don't need to create them. They're called textLabel and detailTextLabel. They're normal labels; you can move them around and make them look like whatever you want. Do that in the cell==nil block.
Then you just need to call cell.textLabel.text = ... and cell.detailTextLabel.text = ... outside the cell==nil block and you're good to go.
If you needed more labels than two, then I would subclass UITableViewCell and create new properties on it so that you can easily reconfigure the cell.
I hope it will work now.Try this.....
- (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];
EventUpcoming *aEventUpcoming = [euEvent objectAtIndex:indexPath.section];
EventWeekly *aEventWeekly = [ewEvent objectAtIndex:indexPath.section];
UILabel *cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 290, 20)];
UILabel *cellSubtitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 290, 20)];
NSString *titleString = [[NSString alloc] init];
NSString *subtitleString = [[NSString alloc] init];
NSString *titleStringUC = [titleString uppercaseString];
NSString *subtitleStringLC = [subtitleString lowercaseString];
cellTitle.text = titleStringUC;
cellTitle.font = [UIFont boldSystemFontOfSize:11];
cellTitle.textColor = [UIColor colorWithRed:142/255.0f green:142/255.0f blue:142/255.0f alpha:1];
cellTitle.shadowColor = [UIColor whiteColor];
cellTitle.shadowOffset = CGSizeMake(1, 1);
cellTitle.backgroundColor = [UIColor clearColor];
cellTitle.tag = 10;
cellSubtitle.text = subtitleStringLC;
cellSubtitle.font = [UIFont boldSystemFontOfSize:11];
cellSubtitle.textColor = [UIColor colorWithRed:177/255.0f green:177/255.0f blue:177/255.0f alpha:1];
cellSubtitle.shadowColor = [UIColor whiteColor];
cellSubtitle.shadowOffset = CGSizeMake(1, 1);
cellSubtitle.backgroundColor = [UIColor clearColor];
cellSubtitle.tag = 11;
tableViewCellSeparator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"TableCellSeparator.png"]];
tableViewCellSeparator.frame = CGRectMake(0, cell.bounds.size.height - 2, 320, 2);
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[cell.contentView addSubview:cellTitle];
[cell.contentView addSubview:cellSubtitle];
[cell.contentView addSubview:tableViewCellSeparator];
}
cellTitle = (UILabel *)[cell.contentView viewWithTag:10];
cellSubtitle = (UILabel *)[cell.contentView viewWithTag:11];
if (segmentedControl.selectedSegmentIndex == 0)
{
Event *aEvent = [aEventUpcoming.event objectAtIndex:indexPath.row];
titleString = aEvent.name;
subtitleString = aEvent.subtitle;
}
else
{
Event *aEvent = [aEventWeekly.event objectAtIndex:indexPath.row];
titleString = aEvent.name;
subtitleString = aEvent.subtitle;
}
return cell;
}

problem with table view grouped table view

tableview problem: i am using 3 uilable for displaying productname, some description and image. all data displayed but when scrolling the table the labels are filled with another text with the actual text.. how can we handle this?
Code:
- (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];
}
UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(2, 2, 41, 41)];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [tableData objectAtIndex:indexPath.row];
NSString *prdStus = [aDict1 objectForKey:#"ProductStatus"];
NSLog(#"product status is %# ",prdStus);
if ([prdStus isEqualToString:#"Orange"]) {
[imageview setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if ([prdStus isEqualToString:#"Green"]) {
[imageview setImage:[UIImage imageNamed:#"Green.png"]];
}
if ([prdStus isEqualToString:#"Red"]) {
[imageview setImage:[UIImage imageNamed:#"Red.png"]];
}
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(46, 0, 220, 12) ];
label2.font = [UIFont systemFontOfSize:12];
label2.text = #"";
if (indexPath.row <[tableData count]) {
label2.text = [aDict1 objectForKey:#"ProductName"];
}
[cell addSubview:label2];
[cell addSubview:imageview];
label2.backgroundColor =[UIColor clearColor];
UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(46, 13, 220, 30) ];
label3.font = [UIFont systemFontOfSize:10];
label3.text = #"";
label3.text = [aDict1 objectForKey:#"ProductDescription"];
[cell addSubview:label3];
return cell;
}
please tell me how to avoid this..
Grouped Table view.
Here is also i am facing same problem.
I am using 4 section
1st and 3rd sections 1 row each,
2nd sec 3 rows,
4th sec 5
when configure the text the first section label displayed on 4th and 3rd section data also displayed on 4th section.
Code
- (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.userInteractionEnabled =NO;
if (indexPath.section == 0)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 2, 294, 40) ];
label.backgroundColor = [UIColor clearColor];
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [detailsArray objectAtIndex:0];
label.text=#"";
label.text =[aDict1 objectForKey:#"ProductName"];
label.numberOfLines = 2;
label.lineBreakMode = UILineBreakModeWordWrap;
[cell addSubview:label];
[label release];
// [cell addSubview:imgview1];
// [imgview1 release];
}
if (indexPath.section ==1 ) {
if (indexPath.row == 0)
{
imgview = [[UIImageView alloc]initWithFrame:CGRectMake(255,2 , 46, 46)];
[cell addSubview:imgview];
[imgview release];
cell.textLabel.text = #"Actual Halal Rating";
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [detailsArray objectAtIndex:0];
NSString *statStr=[[NSString alloc] init];
statStr = [aDict1 objectForKey:#"ProductHalalStatus"];
NSLog(#"status is %#",statStr);
imgview1 = [[UIImageView alloc]initWithFrame:CGRectMake(255,2 , 20, 20)];
if ([statStr isEqualToString:#"Red"]) {
[imgview1 setImage:[UIImage imageNamed:#"Red.png"]];
}
if ([statStr isEqualToString:#"Orange"] ) {
[imgview1 setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if ([statStr isEqualToString:#"Green"]) {
[imgview1 setImage:[UIImage imageNamed:#"Green.png"]];
}
[cell addSubview:imgview1];
[imgview1 release];
}
if (indexPath.row == 1) {
cell.textLabel.text = #"Halal (Permisible)";
[imgview setImage:[UIImage imageNamed:#"Green.png"]];
}
if (indexPath.row == 2) {
cell.textLabel.text = #"Masbooh (Doubtful)";
[imgview setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if (indexPath.row == 3) {
cell.textLabel.text = #"Haram (Not Permisible)";
[imgview setImage:[UIImage imageNamed:#"Red.png"]];
}
}
if (indexPath.section == 2) {
NSDictionary *aDict2 = [[NSDictionary alloc]init];
aDict2 = [detailsArray objectAtIndex:0];
// NSArray *ingrArr =[aDict2 objectForKey:#"IngredientInfo1"];
textview1 =[[UITextView alloc]initWithFrame:CGRectMake(12, 2, 294, 96)];
//textview1.text = ingrStr;
textview1.editable =NO;
[textview1 setFont:[UIFont systemFontOfSize:15]];
[cell addSubview:textview1];
[textview1 release];
}
if (indexPath.section == 3) {
}
return cell;
}
Remove the line, from you code ....
if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
and add the following line
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]

custom cell based on row index iphone

I'm wondering if it is possible to add cell content to a uitableview based on the row index?
For example if it is the first cell (row 0) I want to add an image and text.
If it is the second row I would like to add a button.
For all other rows I would like to just add a line of text.
I tried using indexPath.row. It worked the first time but when I scroll off of the screen and then back up my first image dissapears.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PromoListItem *promo = [promoList objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
AsyncImageView *asyncImageView = nil;
UILabel *label = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(indexPath.row==0)
{
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGRect frame;
frame.origin.x = 0;
frame.origin.y = 0;
frame.size.width = 100;
frame.size.height = 100;
asyncImageView = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImageView.tag = ASYNC_IMAGE_TAG;
[cell.contentView addSubview:asyncImageView];
frame.origin.x = 110;
frame.size.width =100;
label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.tag = LABEL_TAG;
[cell.contentView addSubview:label];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else {
asyncImageView = (AsyncImageView *) [cell.contentView viewWithTag:ASYNC_IMAGE_TAG];
label = (UILabel *) [cell.contentView viewWithTag:LABEL_TAG];
}
NSURL *url = [NSURL URLWithString:promo.imgurl];
[asyncImageView loadImageFromURL:url];
label.text = promo.artistname;
}else
{
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGRect frame;
frame.origin.x = 0;
frame.origin.y = 0;
frame.size.width = 100;
frame.size.height = 100;
//asyncImageView = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
// asyncImageView.tag = ASYNC_IMAGE_TAG;
// [cell.contentView addSubview:asyncImageView];
frame.origin.x = 110;
frame.size.width =100;
label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.tag = LABEL_TAG;
[cell.contentView addSubview:label];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else {
// asyncImageView = (AsyncImageView *) [cell.contentView viewWithTag:ASYNC_IMAGE_TAG];
label = (UILabel *) [cell.contentView viewWithTag:LABEL_TAG];
}
//NSURL *url = [NSURL URLWithString:promo.imgurl];
//[asyncImageView loadImageFromURL:url];
label.text = promo.artistname;
}
return cell;
}
How customized do you want these cells? If you are only adding text, images and accessory buttons, you can create the cell outside of your row check, and then add the needed items inside those if statements.
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSUInteger row = [indexPath row];
switch(row) {
case 0:
cell.textLabel.text = #"row 0";
cell.image
break;
case 1:
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
break;
default:
cell.textLabel.text = [NSString stringWithFormat:#"row %d",row];
break;
}
return cell;
However, the row will change when you start to recycle your cells, you may want to have something in the actual data that indicates how the cell should behave.