Unable to add customization to a specific cell in my table view? - ios

I have a table view that is being populated by the contents of my array _stations.
In total I have over 50 stations (that are automatically fetched via XML), each of course gets its own cell row with a label for its name. The problem I am running into now, is that I have manually added another item to my _stations, so this particular item I would like to stand out from the rest, Ideally I'd like for it to look a little different, perhaps a semi transparent .5 alpha greenColor on the background, and everything else the same.
To do so, I have tried to implement the following code:
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
StationCell* cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (_stations.count == 1) {
// THIS BEING THE SPECIFIC CELL that I have manually added.
cell.backgroundColor = [UIColor greenColor];
}
else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.backgroundColor = [UIColor clearColor];
Station* station = [_stations objectAtIndex:indexPath.row];
delegate* appDelegate = (delegate*)[UIApplication sharedApplication].delegate;
if([station.streamURL isEqualToString:[((AVURLAsset*)(appDelegate.mainPlayer.currentItem.asset)).URL absoluteString]])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
cell.titleLabel.text = station.name;
cell.bitrateLabel.text = [NSString stringWithFormat:#"%# kbps", station.bitRate];
}
return cell;
}
But when I run the app, none of the customization is on the specific cell... Or any cell at all for that matter, but if I replace clearColor with greenColor then it changes all of my cells to greenColor (understandably so)...
How can I customize this specific cell that is sitting in my array in position 1?

I don't think the if condition you have used is correct in your case.
if (_stations.count == 1) {
// THIS BEING THE SPECIFIC CELL that I have manually added.
cell.backgroundColor = [UIColor greenColor];
}
_stations.count will always be 50 or more as you have mentioned in your question. So this condition will never be met.
To modify the first cell of your table you need to use indexpath of the tableview.
Try replacing your if condition with this.
if (indexpath.row == 0) {
// THIS BEING THE SPECIFIC CELL that I have manually added.
cell.backgroundColor = [UIColor greenColor];
}
indexpath.row gives you the index of the cell in that tableView. If its the the first cell then just modify it.

try this . . .
(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
StationCell* cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"cell";
}
if (_stations.count == 1) {
// THIS BEING THE SPECIFIC CELL that I have manually added.
cell.backgroundColor = [UIColor greenColor];
}
else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.backgroundColor = [UIColor clearColor];
Station* station = [_stations objectAtIndex:indexPath.row];
delegate* appDelegate = (delegate*)[UIApplication sharedApplication].delegate;
if([station.streamURL isEqualToString:[((AVURLAsset*)(appDelegate.mainPlayer.currentItem.asset)).URL absoluteString]])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
cell.titleLabel.text = station.name;
cell.bitrateLabel.text = [NSString stringWithFormat:#"%# kbps", station.bitRate];
}
return cell;

Related

UIButton gets created twice on cell reload

I have a UIButton inside a UITableViewCell. When the app is first launched, it works as expected, where I created it's frame.
When I scroll pass the cell which holds the button, it creates a second instance of the button slightly below the button.
Here's a video to illustrate my problem: http://pixori.al/DJ1k
Here's the code for the UITableViewCell and also how I populate the cells.
Not sure why it's behaving like this.
#pragma mark - UITableViewDataSource
// 3 sections, (1 = mistarOverview) (2 = hourlyForecast) (3 = dailyForecast)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return MAX(6,6) + 1; //TODO add getNumberOfClasses for people with 7 or 8 classes
} else if (section == 1) {
return MIN([[MAManager sharedManager].hourlyForecast count], 6) + 1;
} else {
return MIN([[MAManager sharedManager].dailyForecast count], 6) + 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Redefine layout variables in method from `viewDidLoad`
CGFloat inset = 20; // For padding
if (! cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
// Sets up attributes of each cell
cell.selectionStyle = UITableViewCellSelectionStyleNone; //TODO none
cell.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
QBFlatButton* loginButton = nil;
if (indexPath.section == 0) {
if (indexPath.row == 0) {
[self configureHeaderCell:cell title:#"Grades"];
if ([cell.textLabel.text isEqual: #"Grades"] && (!loginButton) && (indexPath.row == 0) && (indexPath.section == 0)) {
UIView *cellView = cell.contentView;
CGRect loginButtonFrame = CGRectMake((cellView.frame.size.width - (80 + inset)), 18, 80, (cellView.frame.size.height));
loginButton = [[QBFlatButton alloc] initWithFrame:loginButtonFrame];
[loginButton addTarget:self action:#selector(loginButtonWasPressed)forControlEvents:UIControlEventTouchUpInside];
loginButton.faceColor = [UIColor grayColor];
loginButton.sideColor = [UIColor clearColor];
loginButton.radius = 6.0;
loginButton.margin = 4.0;
loginButton.depth = 3.0;
loginButton.alpha = 0.3;
loginButton.titleLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:20];
[loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[loginButton setTitle:#"Login" forState:UIControlStateNormal];
[cellView addSubview:loginButton];
}
} else {
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.text = [NSString stringWithFormat:#"Period %ld A+", (long)indexPath.row];
cell.detailTextLabel.text = #"Class name";
//TODO get grades and config using method (TB Created)
}
} else if (indexPath.section == 1) {
if (indexPath.row == 0) {
[self configureHeaderCell:cell title:#"Hourly Forecast"];
}
else {
// Get hourly weather and configure using method
MACondition *weather = [MAManager sharedManager].hourlyForecast[indexPath.row - 1];
[self configureHourlyCell:cell weather:weather];
}
}
else if (indexPath.section == 2) {
if (indexPath.row == 0) {
[self configureHeaderCell:cell title:#"Daily Forecast"];
}
else if (indexPath.section == 2) {
// Get daily weather and configure using method
MACondition *weather = [MAManager sharedManager].dailyForecast[indexPath.row - 1];
[self configureDailyCell:cell weather:weather];
}
}
return cell;
}
Implement the following UITableView Delegate Method
-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//In here, check the index path. When you have the cell that contains the button, pop it out from there by using [button removeFromSuperView];
}
Your problem occurs when you dequeue the cell. Since the cell is being reused, it already has the button and you're simply re-adding it again. This will solve your issue. However, I'd recommend you create a subclass for the UITableViewCell, and in it's prepareForReuse method, pop the button out. Up to you. Both will work.
Table view cells are not just deallocated then they move out of visible area. They are stored for reusing and then returned in tableView dequeueReusableCellWithIdentifier:CellIdentifier];
So you need to clean your cells after using or before reusing. There are several ways:
1.Add tag to your button when you create it
loginButton.tag = SOME_TAG;
just after
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
search for view with this tag
loginButton = [cell viewWithTag:SOME_TAG];
if loginButton != nil you can reuse it or remove from cell and then create a new one.
2.Implement UITableViewDelegate method
-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
and erase login button inside it.
3.Create custom UITableViewCellclass and implement prepareForReuse method.
You're adding the button every time you return a cell in this method. If you scroll the cell off the screen and back on, this method is called again for the same index path, and you will add the button again.
You declare the variable, do nothing with it, then check if it is nil. It will always be nil, so you always add the button.
A quick and dirty solution is to give the button a tag, then check for its existence using viewWithTag:.
A better solution is to make a custom cell subclass, and set one-time properties like this in the init method. Your cell contents seem very different for each section as well, so use different reuse identifiers for each section, and possibly a different cell subclass. Clearing out sub views is expensive and could hurt your scrolling performance.
When you run your project first time then cellForRowAtIndexPath is called.....
Then whenever you scroll tableView it again calls cellForRowAtIndexPath and reload data automatically..
So you have to take CellIdentifier as unique for each cell.
you have to remove static keyword from
static NSString *CellIdentifier = #"CellIdentifier";
now you have
NSString *CellIdentifier = #"CellIdentifier";
only this things
Now you have to write like below
NSString *CellIdentifier = [NSString stringWithFormat:#"%#",indexPath];
Now Enjoy.....

How to mange cell color style while navigating back , each time

I have one table view in which i am displaying some record. And navigte to second view, in second view controller we have four options as primary, secondary, tertia, quatrnary. when user select any of this optin it will navigate to back and selected cell color will change.
All option is working well. but i stuck at following issue as,
suppose user select first cell and set this as pri, it will navigate back and color will be red, BUT when user slected another cell (supoose 5 cell) and again set as primary then cell 1 will remaining same as red. i dont want this. at a time user will set noly one record as pri/sec/ter/quaternary.
How i will manage this?? Tried to relaod table data, but not working?? while navigating back i am using below code in viewwill appear
if (singltong.primary == indes) {
[tbleMasjidnames cellForRowAtIndexPath:tableSelection].backgroundColor = [UIColor colorWithRed:13.0f/255.0f green:159.0f/255.0f blue:78.0f/255.0f alpha:1.0f];
}
else if (singltong.secondary == indes){
[tbleMasjidnames cellForRowAtIndexPath:tableSelection].backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:33.0f/255.0f blue:59.0f/255.f alpha:1.0f];
}
else if (singltong.tertiary == indes){
[tbleMasjidnames cellForRowAtIndexPath:tableSelection].backgroundColor = [UIColor colorWithRed:23.0f/255.0f green:153.0f/255.0f blue:221.0f/255.0f alpha:1.0f];
}
else if (singltong.quaternary == indes){
[tbleMasjidnames cellForRowAtIndexPath:tableSelection].backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:150.0/255.0 blue:23.0f/255.0f alpha:1.0f];
}
//********************Cell for row****************
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"MasjidCell"; // Custom cell for masjid Name
MasjidListCell *cell = (MasjidListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor greenColor];
if (cell == nil){
NSArray *nib=[[NSBundle mainBundle] loadNibNamed:#"MasjidCell" owner:self options:nil];
cell = nib[0];
}
cell.selectionStyle=UITableViewCellSelectionStyleNone;
//if search is on then get data from search result array else from shared instance
if (_isSearchOn) {
if ([searchResults count]==0) {
cell.lblMasjidName.text=#"No Record Found.";
}
else{
cell.lblMasjidName.text = [searchResults objectAtIndex:indexPath.row];
}
}
else{
cell.lblMasjidName.text = singltong.MasjidNames[indexPath.row];
cell.lblLocalArea.text = singltong.masjidLocalArea[indexPath.row];
cell.lblCountry.text = singltong.masjidCountry[indexPath.row];
}
return cell;
}//end of method
If your cells are bound to Entities in a Database, you have to run a logic in the priority selection controller where after the selection, other objects with this priority are set back or act like you want. If you use the NSFetchedResultsController, your data is hold up-to-data and you can do a default handling in the cellForRowAtIndexpath method
if ([entity.prio intValue] == 1)
{
// set your cell settings
}
all of your affected cells have to be updated, so maybe a [tableView reloadData]; in viewWillAppear will help
update:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[tbleMasjidnames reloadData];
// ...
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// ... get/create cell instance
if (_isSearchOn)
{
if ([searchResults count]==0)
{
cell.lblMasjidName.text=#"No Record Found.";
}
else
{
cell.lblMasjidName.text = [searchResults objectAtIndex:indexPath.row];
}
}
else
{
cell.lblMasjidName.text = singltong.MasjidNames[indexPath.row];
cell.lblLocalArea.text = singltong.masjidLocalArea[indexPath.row];
cell.lblCountry.text = singltong.masjidCountry[indexPath.row];
switch(indexPath.row)
{
case singltong.primary:
cell.backgroundColor = [UIColor colorWithRed:13.0f/255.0f green:159.0f/255.0f blue:78.0f/255.0f alpha:1.0f];
break;
case singltong.secondary:
cell.backgroundColor = [[UIColor colorWithRed:255.0f/255.0f green:33.0f/255.0f blue:59.0f/255.f alpha:1.0f];
break;
// ...
default:
cell.backgroundColor = [UIColor whiteColor]; // or other default
break;
}
}
}
but you still have to implement correct handling logic in your singltong class to make this working.

why my uitableview cell row is repeating subtitles

In my uitableview I have two sections
first is fetched from core data
other is added through textfield which is stored in NSMutableArray(otherFriends)
here is my code
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if([otherFriends count]>0)
{
return 2;
}
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
if(otherFriends == 0)
{
return [[[[self fetchedResultsController]sections]objectAtIndex:0]numberOfObjects];
}
return [otherFriends count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newGroupCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Light" size:20.0];
cell.textLabel.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.0f];
if(indexPath.section == 0)
{
user = [[self fetchedResultsController] objectAtIndexPath:indexPath];
cell.textLabel.text = user.name;
cell.detailTextLabel.text = user.primaryResource.status;
[cell.imageView setFrame:CGRectMake(0, 0, 50, 50)];
[cell.imageView.layer setMasksToBounds:YES];
if (user.photo != nil)
{
cell.imageView.image = user.photo;
}
else
{
cell.imageView.image = [UIImage imageNamed:#"defaultPerson"];
}
}
else
{
cell.textLabel.text = [otherFriends objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:#"defaultPerson"];
}
return cell;
}
First section also have subtitles but second section cells have no subtitles
when I am adding new friend it works fine till all rows are visible, but when adding new friend and that row is not visible and to view that row I must scroll, then this row show the subtitle of first row in section 0(the very first cell) and its repeating in section 1 third row. Only subtitle is repeating but the main text is not.
For several hours I am trying to figure out this but no luck.
This is because in your else branch you are not setting the cell.detailTextLabel.text.
When a cell gets recycled, the old detailTextLabel stays there. You need to set all properties of the cell in both branches of the conditionsl, on the chance that it has been recycled.
if(indexPath.section == 0)
{
user = [[self fetchedResultsController] objectAtIndexPath:indexPath];
cell.textLabel.text = user.name;
cell.detailTextLabel.text = user.primaryResource.status;
[cell.imageView setFrame:CGRectMake(0, 0, 50, 50)];
[cell.imageView.layer setMasksToBounds:YES];
if (user.photo != nil)
{
cell.imageView.image = user.photo;
}
else
{
cell.imageView.image = [UIImage imageNamed:#"defaultPerson"];
}
}
else
{
cell.textLabel.text = [otherFriends objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:#"defaultPerson"];
// ADDED
cell.detailTextLabel.text = #"";
// You may also need to adjust the frame of the cell.imageView
// because it could have been recycled.
}
Cells get reused. Since you are using the same cells for both sections, you must be sure to set/reset the same set of cell properties in all conditions.
The problem is when the cell is used for section 1, you don't reset the detailTextLabel. In your else block, add:
cell.detailTextLabel.text = nil;
This ensures that in all cases you are setting the textLabel, detailTextLabel, and the imageView properties for the reused cells.

iOS Xcode - Grouped TableView separator line display

Am I the only one who get this problem?
I have few sections and few rows in grouped table view, for registration page. When I slide up and down the page, there's strange separator bold line appear between two cells. Some of the cell sinks like it has been pressed. Is this a iOS 5.0 bug? I have worked for 3 days for this little problem. Please help!
I have try
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
and
self.tableView.separatorColor = [UIColor lightGrayColor];
None of them work.
[Edited]
Paul Peelen you're right and I know what you meant, but I don't have the knowledge to continue forward. Before I comment the "if(cell == nil)", everything is the same as what you've said. But after I comment it, the label is displayed well and no problem with the separator line anymore, but when I insert the texts into the textField and slide down, and up again, the textField's text is gone and been refreshed. How do I solve this one?
Below is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"LabelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Here's the problem!
if(cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UILabel *keyLbl = [[UILabel alloc] initWithFrame:CGRectMake(15, 8, 100, 30)];
keyLbl.font = [UIFont fontWithName:#"Futura-CondensedExtraBold" size:15.0];
keyLbl.textColor = [UIColor colorWithRed:0.275 green:0.275 blue:0.275 alpha:0.9];
keyLbl.backgroundColor = [UIColor clearColor];
valTxtField = [[UITextField alloc] initWithFrame:CGRectMake(120, 5, 180, 30)];
valTxtField.font = [UIFont fontWithName:#"Futura-CondensedExtraBold" size:18.0];
valTxtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
valTxtField.delegate = self;
valTxtField.returnKeyType = UIReturnKeyDone;
valTxtField.autocorrectionType = UITextAutocorrectionTypeNo;
valTxtField.autocapitalizationType = UITextAutocapitalizationTypeNone;
if(indexPath.section == 0)
{
if(indexPath.row == 0)
{
keyLbl.text = NSLocalizedString(#"REGIS_EMAIL", nil);
email_TextField = valTxtField;
}
else if(indexPath.row == 1)
{
keyLbl.text = NSLocalizedString(#"REGIS_RE_EMAIL", nil);
reEmail_TextField = valTxtField;
}
else if(indexPath.row == 2)
{
keyLbl.text = NSLocalizedString(#"REGIS_PWD", nil);
password_TextField = valTxtField;
valTxtField.secureTextEntry = YES;
}
else if(indexPath.row == 3)
{
keyLbl.text = NSLocalizedString(#"REGIS_RE_PWD", nil);
rePassword_TextField = valTxtField;
valTxtField.secureTextEntry = YES;
}
}
else if(indexPath.section == 1)
{
if(indexPath.row == 0)
{
keyLbl.text = NSLocalizedString(#"REGIS_FIRSTNAME", nil);
firstName_TextField = valTxtField;
}
if(indexPath.row == 1)
{
keyLbl.text = NSLocalizedString(#"REGIS_LASTNAME", nil);
lastName_TextField = valTxtField;
}
if(indexPath.row == 2)
{
keyLbl.text = NSLocalizedString(#"REGIS_POSTCODE", nil);
postCode_TextField = valTxtField;
}
if(indexPath.row == 3)
{
keyLbl.text = NSLocalizedString(#"REGIS_GENDER", nil);
gender_TextField = valTxtField;
}
if(indexPath.row == 4)
{
keyLbl.text = NSLocalizedString(#"REGIS_DOB", nil);
DOB_TextField = valTxtField;
}
if(indexPath.row == 5)
{
keyLbl.text = NSLocalizedString(#"REGIS_MOBILE", nil);
mobile_TextField = valTxtField;
}
}
[cell addSubview:keyLbl];
[cell addSubview:valTxtField];
[keyLbl release];
[valTxtField release];
return cell;
}
Do you want a separator colour at all? You could always set it to clear if not.
self.tableView.separatorColor = [UIColor clearColor];
That is most likely due to that you are using different settings on your cells. Since cells are reused and not created as new ones for each cell, you can get a reused cell with different settings on them which have been set by the last cell whom used it.
So for instance, lets say 4 cells are visible in your UITableView. That means that either 6 or 7 are loaded in the memory but not yet visible. Lets say you have a list of 10 cells total, then when you scroll down, cell #8 will only be loaded into the memory when it should be shown, releasing any other cells that should not be shown anymore. So cell #8 will get the former cell #0's cell. If you then set in #8 that the background color should be red, and you scroll up again, you will see that cell #0 will also have a red background, unless you tell cell #0 to have a white background, then it will be white.
The same goes for seperators ect.
Simple way to test this is to make you "cellIdentifier" unique.
OK, this is mainly because the cell identifier. Since the table view recycle its contents to display every time I scroll up and down, and if I use the same cell identifier, strange behaviour like I mentioned above will happen.
This is my solution to all the strange things happen on displaying the table view:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Here the solution:
NSString *CellIdentifier = [NSString stringWithFormat:#"RCell%1dR%1d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//your tableView code...
}

dequeueReusableCell causing weird behavior

i'am creating an iOS application which is similar to bbc application
- I have a table view which has two section
- 1st section contains cells containing scrollview wid images
- 2nd section contains expandable cells which contains scrollview did images
so the problem is that
when i use the dequereusable its showing weird behaviors like when the bottommost cell in the table is expanded the first cell in the first gets cleared etc etc
so i have just stopped using the queue and everything started working fine
but now when i added images after scrolling the cells which is not in the view gets refreshed and its
taking a lot of time to load
so could kindly guide me how to use the queue wisely in the code
described below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier=#"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell== nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"hai"] autorelease];
///[here a different name has been used for the reuse identifier];////
if ([self tableView:tableView inSection2:indexPath.section]) {
Coffee *co =[appDelegate.coffeeArray2 objectAtIndex:indexPath.section-s1Count-1];
cell.textLabel.text=co.coffeeName;
}
if ([self tableView:tableView inSection1:indexPath.section]) {
Coffee *co =[appDelegate.coffeeArray1 objectAtIndex:indexPath.section];
cell.textLabel.text = co.coffeeName;
CGRect cellname = CGRectMake(5, 0, 290, 25);
UILabel *cellabel = [[[UILabel alloc] initWithFrame:cellname] autorelease];
cellabel.backgroundColor = [UIColor whiteColor];
cellabel.font = [UIFont italicSystemFontOfSize:20];
cellabel.textColor=[UIColor blueColor];
cellabel.highlightedTextColor = [UIColor clearColor];
cellabel.text=co.coffeeName;
[cell.contentView addSubview:cellabel];
}
// Configure the cell...
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// first row
// only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
cell.accessoryView = [myuicontroller accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
cell.accessoryView = [myuicontroller accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
}
else
{
// all other rows
cell.accessoryView = nil;
cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;
CGRect cellname = CGRectMake(5, 0, 290, 25);
UILabel *cellabel = [[[UILabel alloc] initWithFrame:cellname] autorelease];
cellabel.backgroundColor = [UIColor whiteColor];
cellabel.font = [UIFont italicSystemFontOfSize:13];
cellabel.textColor=[UIColor blueColor];
cellabel.highlightedTextColor = [UIColor clearColor];
// cellabel.text =[NSString stringWithFormat:#"category"];
[cell.contentView addSubview:cellabel];
myscrollView *svb;
svb=[[myscrollView alloc]initwitharray:appDelegate.newscat1];
}else{
myscrollView *s;
NSLog(#"inside the textlabel ext%#",cell.textLabel.text);
NSLog(#"count of array %d",[appDelegate.newscat1 count]);
NSString *cat=cell.textLabel.text;
[cell.contentView addSubview:s];
}
}
return cell;
}
You need to set the alternative reuse identifier before you dequeue the cell. At the moment you are dequeuing a cell with identifier "cell" regardless of the section you are in, so you will often be returning a section 0 cell for a section 1 part of the table.
So, branch your code so that you do different things depending on the value of indexPath.section:
if (indexPath.section == 0)
cellIdentifier = #"thisCell";
else
cellIdentifier = #"otherCell";
Then dequeue your cell, if it is nil, create with the same cell identifier variable above.
You should only be adding subviews inside your (cell = nil) code - otherwise you will end up with cells with lots of overlapping subviews and will be wasting memory. If a cell has been dequeued, you just configure the existing subviews, you don't make new ones. You can assign tags to your subviews as you add them to assist with this.

Resources