Table view cell management has driving me crazy from past two days. Please check the code below and I will explain you the problem in detail..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *nameLabel,*sugarLabel,*searchNameLabel,*searchSugarLabel;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
CGFloat height = 20;
CGRect frame = CGRectMake(10.0f, 10.0f, width, height);
if(isSearchOn)
{
searchNameLabel = [[UILabel alloc] initWithFrame:frame];
searchNameLabel.textColor = [UIColor blackColor];
searchNameLabel.backgroundColor = [UIColor clearColor];
searchNameLabel.textAlignment = UITextAlignmentLeft;
searchNameLabel.font = [UIFont systemFontOfSize:14.0f];
searchNameLabel.tag=260;
[cell.contentView addSubview:searchNameLabel];
[searchNameLabel release];
searchSugarLabel= [[UILabel alloc] initWithFrame:frame];
searchSugarLabel.textColor = [UIColor blackColor];
searchSugarLabel.backgroundColor = [UIColor clearColor];
searchSugarLabel.textAlignment = UITextAlignmentLeft;
searchSugarLabel.font = [UIFont systemFontOfSize:14.0f];
searchSugarLabel.tag=160;
[searchSugarLabel setHidden:YES];
[cell.contentView addSubview:searchSugarLabel];
[searchSugarLabel release];
}
else{
nameLabel = [[UILabel alloc] initWithFrame:frame];
nameLabel.textColor = [UIColor blackColor];
nameLabel.backgroundColor = [UIColor clearColor];
nameLabel.textAlignment = UITextAlignmentLeft;
nameLabel.font = [UIFont systemFontOfSize:14.0f];
nameLabel.tag=60;
[cell.contentView addSubview:nameLabel];
[nameLabel release];
sugarLabel= [[UILabel alloc] initWithFrame:frame];
sugarLabel.textColor = [UIColor blackColor];
sugarLabel.backgroundColor = [UIColor clearColor];
sugarLabel.textAlignment = UITextAlignmentLeft;
sugarLabel.font = [UIFont systemFontOfSize:14.0f];
sugarLabel.tag=160;
[sugarLabel setHidden:YES];
[cell.contentView addSubview:sugarLabel];
[sugarLabel release];
}
}
else {
if(isSearchOn)
{
searchNameLabel=(UILabel *)[cell.contentView viewWithTag:260];
searchSugarLabel=(UILabel *)[cell.contentView viewWithTag:160];
}
else{
nameLabel=(UILabel *)[cell.contentView viewWithTag:60];
sugarLabel=(UILabel *)[cell.contentView viewWithTag:160];
}
}
if (isSearchOn) {
cellValue = [searchResult objectAtIndex:indexPath.row];
searchSugarLabel.text=cellValue.sugarId;
NSString *searchText = [NSString stringWithFormat:#"%# %#", cellValue.firstName, cellValue.lastName];
searchNameLabel.text=searchText;
NSLog(#"%#",searchNameLabel.text);
NSLog(#"%#",searchSugarLabel.text);
}
else {
NSString *contact=[contactKeys objectAtIndex:[indexPath section]];
NSArray *contactSection=[contactNames objectForKey:contact];
sugar=[db getSugarId:#"Contacts" bySection:contact andIndex:indexPath.row];
NSString *cellText = [contactSection objectAtIndex:[indexPath row]];
// split the text by the : to get an array containing { "AAA", "BBB" }
NSArray *splitText = [cellText componentsSeparatedByString:#":"];
// form a new string of the form "BBB AAA" by using the individual entries in the array
NSString *contactText = [NSString stringWithFormat:#"%# %#", [splitText objectAtIndex:1], [splitText objectAtIndex:0]];
nameLabel.text = contactText;
sugarLabel.text = sugar;
}
return cell;
}
Contacts is a class which has the properties firstName,lastName and sugar id in it..I am assigning the properties of a contacts class to the variables in the database method and returning an array of contact objects. searchResult is now an array of contact objects.The problem is when I logged the contents on the console the database gets everything in it and returns an array of contacts.The contacts in the searchResult points to different memory locations but when I try to debug the cellForRowAtIndexPath method after it gets 6 contacts..the 7th contact points to the same memory location as the 1st and it repeats thus in the searchNameLabel.text it returns a null and indexPath points to nil...I think it is cell re use issue and I accept that I am very bad in that..I need to figure this out as I am going to finish off my project with this...please guys help me...
This happens only when I try to search for the contacts. It works fine when I try to load all the contacts onto the table..
You are initializing your subviews in the if(cell== nil) block, but in the corresponding else-block, you overwrite them again.
You should rethink your design: Do not load different views by searchon, but set their properties depending on searchon
if(cell == nil){
//do all initializing
}
if(searchon){
//set view/label properties for searching style
} else {
//set view/label properties for not-searching style
}
another approach could be to have totally separated NIB files for the searchon/!searchon
if(searchon){
static NSString *SearchOnCellIdentifier = #"SearchOnCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SearchOnCellIdentifier];
if (cell == nil){
//load cell from extra nib
}
} else {
static NSString *SearchOFFCellIdentifier = #"SearchOFFCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SearchOFFCellIdentifier];
if (cell == nil){
//load cell from extra nib
}
}
NOTE: I never did that and it is not tested.
Related
In my app i am customised the UITableView Cell with four UITextViews. Whenever i added data to the tableview and reload it. The text in the UITableViewCell get override with the previous texts.
I tried different approaches but couldn't figure out what was the problem.
I am using TableView in View Controller.
Here is the Code i used in my table View cell?
if ( [tableView isEqual:self.tableActions])
{
//Setting the text empty
static NSString *CellIdentifier = #"ActionsIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
NSLog(#"Index Path %i",[indexPath row]);
ActionDetails *actiondetails = [actionArray objectAtIndex:[indexPath row]];
NSLog(#"Action Text %#",actiondetails.actions);
//Actions
actionText=[[UITextView alloc] initWithFrame:CGRectMake(10, 5, 230,30)];
actionText.font = [UIFont systemFontOfSize:17.0];
actionText.editable = NO;
actionText.textColor=[UIColor blackColor];
actionText.text = actiondetails.actions ;
actionText.userInteractionEnabled = NO;
actionText.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:actionText];
//Owner
ownerBy=[[UITextView alloc] initWithFrame:CGRectMake(230, 5, 230,30)];
ownerBy.font = [UIFont systemFontOfSize:17.0];
ownerBy.textColor=[UIColor blackColor];
ownerBy.textAlignment = UITextAlignmentCenter;
ownerBy.text = actiondetails.owner;
ownerBy.editable = NO;
ownerBy.userInteractionEnabled = NO;
ownerBy.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:ownerBy];
}
ScreenShot
Thanks for your help guys.
Much Appreciated.
This happened to me a other day, the solution that I came up with was removing all subview from the cell after creating the cell in the if statement.
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
Remove cell identifier of Tableview otherwise take Customcell for the Tableview..
Just simple try this way :
{
//Setting the text empty
static NSString *CellIdentifier = #"ActionsIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
**// if(cell == nil) // comment this line in your code ,its work
// {**
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
**// }**
NSLog(#"Index Path %i",[indexPath row]);
ActionDetails *actiondetails = [actionArray objectAtIndex:[indexPath row]];
NSLog(#"Action Text %#",actiondetails.actions);
//Actions
actionText=[[UITextView alloc] initWithFrame:CGRectMake(10, 5, 230,30)];
actionText.font = [UIFont systemFontOfSize:17.0];
actionText.editable = NO;
actionText.textColor=[UIColor blackColor];
actionText.text = actiondetails.actions ;
actionText.userInteractionEnabled = NO;
actionText.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:actionText];
//Owner
ownerBy=[[UITextView alloc] initWithFrame:CGRectMake(230, 5, 230,30)];
ownerBy.font = [UIFont systemFontOfSize:17.0];
ownerBy.textColor=[UIColor blackColor];
ownerBy.textAlignment = UITextAlignmentCenter;
ownerBy.text = actiondetails.owner;
ownerBy.editable = NO;
ownerBy.userInteractionEnabled = NO;
ownerBy.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:ownerBy];
}
You are reusing the cell. Reused cell already has UITextview added to it.So you are overriding on it.
You must shift all your code of creating and adding UITextView to.
If(cell==nil)
{
}
After which you only need to set the Text to UITextview.
when your view did appear write reload your table view.
-(void)viewDidAppear:(BOOL)animated {
[tableView reloadData];
}
change your cellForRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// your code
}
// your code
return cell;
}
for (id vw in [[cell contentView] subviews]) {
if ([vw isKindOfClass:[UILabel class]])
{
UILabel *label = (UILabel *)vw;
[label removeFromSuperview];
}
}
for (id vw in [cell subviews]) {
if ([vw isKindOfClass:[UILabel class]])
{
UILabel *label = (UILabel *)vw;
[label removeFromSuperview];
}
}
I have a UITableView with regular UITableViewCell, but I don't use any of UITableViewCell's lables. I just use the cell to embed a label and a UITextField to input some data. Problem is when you scroll up or scroll down and the UITableviewCell redraws itself, it draws an overlapping UITextFieldView over the old one and you see doubles! I'm thinking that maybe since I do put these UITextFields into a dictionary, it might save the textfield with a strong pointer, and try to make another one and just overlap. Anyone have any suggestions?
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
//cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
// save to dictionary, using a dictionary because not certain if this is created in order to use an Array
[self.textFieldDict setObject:cellTextField forKey:[[NSNumber alloc] initWithInteger:indexPath.row]];
return cell;
}
You have not initialized your cell.Try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//It will check whether cell in there or not, then deque the cell...
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
//cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
return cell;
}
Either don't use reusability and always alloc the cell at each time or
make a check after dequeue (like this)
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
// make text field and label an add tag
}
//and outside this by using tag fetch the labels and textField and clear the textFields.
You forgot to put the condition like this:
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];
}
Used this as a reference: add subviews to UITableViewCell
I just first checked to see if this view was added from before, and if it was, then don't add it again. It has nothing to do with the cell being nil. Unless I missed something? all I know is that this seems to be working fine, now.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
if (![cell viewWithTag:1])
{
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
cellTextField.tag = 1; //set tag to 1
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
// save to dictionary, using a dictionary because not certain if this is created in order to use an Array
[self.textFieldDict setObject:cellTextField forKey:[[NSNumber alloc] initWithInteger:indexPath.row]];
}
return cell;
}
My tableview gets duplicated when I use [tableview reloadData].I used this to refresh the tableview when I move back.How could I overcome the issue?
This is my code.
#define kMyTag 1
#define despTag 2
#define subTag 3
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.tableview reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
AsyncImageView *asyncImageView = nil;
UILabel *label = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] ;
UILabel *mainLabel=[[UILabel alloc]init];
mainLabel.tag = kMyTag; // define kMyTag in your header file using #define
mainLabel.frame=CGRectMake(95, 0, 170, 30);
mainLabel.font = [UIFont boldSystemFontOfSize:14];
mainLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:mainLabel];
UILabel *despLabel=[[UILabel alloc]init];
despLabel.tag=despTag;
despLabel.frame=CGRectMake(95, 25, 190, 20);
despLabel.font= [UIFont systemFontOfSize:12];
despLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:despLabel];
} else {
label = (UILabel *) [cell.contentView viewWithTag:LABEL_TAG];
}
switch([indexPath section]){
case 0:
{
NSString *urlString = [img objectAtIndex:indexPath.row];
urlString=[urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
tname=[mname objectAtIndex:indexPath.row];
tprice=[mprice objectAtIndex:indexPath.row];
tquan=[mquan objectAtIndex:indexPath.row];
tspice=[mspice objectAtIndex:indexPath.row];
UILabel *mainLabel=(UILabel *)[cell.contentView viewWithTag: kMyTag];
mainLabel.text = [NSString stringWithFormat:#"%#",tname];
UILabel *despLabel=(UILabel *)[cell.contentView viewWithTag: despTag];
despLabel.text = [NSString stringWithFormat:#"Qty :%# Spice: %#",tquan,tspice];
UILabel *subLabel=(UILabel *)[cell.contentView viewWithTag: subTag];
float pric=[tprice floatValue];
subLabel.text = [NSString stringWithFormat:#"Price :%# %.2f",currencyType, pric];
}
}
}
Overcomes the issue by removing all the objects from array,then reselects the DB table & reloads uitableview.
it happens because you are not passing any value in dequeueReusableCellWithIdentifier
pass a string value and then use it in reuseIdentifier also
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;
}
So I have some issues with my tableview. I have a custom label that I put into a tableview cell to add a little better graphics than the standard UItableviewcell. However, I was running into my first problem,
the text labels that I had on the cells were changing with and over writing each other upon scrolling, only when the cells had moved off screen and then came back. Upon some research I found that maybe it had something to do with dequeueReusableCellWithIdentifier: so I adjusted my code. this is where problem two comes in.
When I load the table everything is in its right place, correct looking and all. However when I start to scroll down I can get to all of my cells except the last one, it will go to the very bottom of the 8th cell and freeze, but I should have 9 cells loaded.
I am quite confused by some of this, could anyone provide some code or guidance to help me along?
Thanks.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Run");
CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *keys = [[appDelegate rowersDataStore] allKeys];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure the cell...
label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 15, cell.bounds.size.width - 10, 30)] autorelease];
label.font = [UIFont boldSystemFontOfSize:16];
label.backgroundColor = [UIColor clearColor];
label.shadowColor = [UIColor colorWithWhite:1.0 alpha:0.5];
label.shadowOffset = CGSizeMake(0,1);
label.textColor = [UIColor colorWithRed:0x4c/255.0 green:0x4e/255.0 blue:0x48/255.0 alpha:1.0];
switch (indexPath.section) {
case 0:
label.frame = CGRectMake(0, 15, cell.bounds.size.width - 10, 30);
label.textAlignment = UITextAlignmentCenter;
break;
case 1:
label.textAlignment = UITextAlignmentLeft;
UIImage *accessoryImage = [UIImage imageNamed:#"content_arrow.png"];
UIImageView *accessoryView = [[UIImageView alloc] initWithImage:accessoryImage];
cell.accessoryView = accessoryView;
[accessoryView release];
break;
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
UIImage* img = [UIImage imageNamed:#"odd_slice.png"];
imgView.image = img;
cell.backgroundView = imgView;
[imgView release];
//Selected State
UIImage *selectionBackground = [UIImage imageNamed:#"row_selected.png"];
UIImageView *selectionView = [[UIImageView alloc] initWithFrame:cell.frame];
selectionView.image = selectionBackground;
cell.selectedBackgroundView = selectionView;
[selectionView release];
}
switch (indexPath.section) {
case 0:
[label setText:#"Click to add new rower"];
break;
case 1:
[label setText:[[[appDelegate rowersDataStore] objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:#"Name"]];
break;
}
//Adds Text
[cell addSubview:label];
return cell;
}
I see several issues here. First, the general structure of this method should be...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
// Attempt to dequeue the cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// If cell does not exist, create it, otherwise customize existing cell for this row
if (cell == nil) {
// Create cell
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure cell:
// *** This section should configure the cell to a state independent of
// whatever row or section the cell is in, since it is only executed
// once when the cell is first created.
}
// Customize cell:
// *** This section should customize the cell depending on what row or section
// is passed in indexPath, since this is executed every time this delegate method
// is called.
return cell;
}
Basically, UITableView uses a single UITableViewCell instance to draw every cell in the table view. So, when you first create this cell, you should configure it to a state that is common to all cells that will use this instance, independent of whatever row or section is passed in indexPath. In your example, this involves creating the label, image, and background image instances and adding them as subviews to the cell.
Once the cell is created (aka outside the if (cell == nil) statement), you should customize its properties according to how the cell should look for the specific row and section contained in indexPath. Since you want to access your custom label in this part of the code, I assigned a tag value to it so that we can access it beyond the code segment where it was created using viewWithTag:. Once we have the label, we can customize it according to the section as well as do anything else we want, such as customize the accessory view.
I slightly modified/cleaned up your code below. This is by far not the most efficient or elegant way to do what you want to do, but I was trying to keep as much of your code as possible. I haven't tested this, but if you try it it should work:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Run");
CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *keys = [[appDelegate rowersDataStore] allKeys];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure the cell...
UILabel *label;
label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 15, cell.bounds.size.width - 10, 30)] autorelease];
label.font = [UIFont boldSystemFontOfSize:16];
label.opaque = NO;
label.backgroundColor = [UIColor clearColor];
label.shadowColor = [UIColor colorWithWhite:1.0 alpha:0.5];
label.shadowOffset = CGSizeMake(0,1);
label.textColor = [UIColor colorWithRed:0x4c/255.0 green:0x4e/255.0 blue:0x48/255.0 alpha:1.0];
label.tag = 100;
[cell addSubview:label];
[label release];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
UIImage* img = [UIImage imageNamed:#"odd_slice.png"];
imgView.image = img;
cell.backgroundView = imgView;
[imgView release];
//Selected State
UIImage *selectionBackground = [UIImage imageNamed:#"row_selected.png"];
UIImageView *selectionView = [[UIImageView alloc] initWithFrame:cell.frame];
selectionView.image = selectionBackground;
cell.selectedBackgroundView = selectionView;
[selectionView release];
}
UILabel *lbl = (UILabel *)[cell viewWithTag:100];
switch (indexPath.section) {
case 0:
cell.accessoryView = nil;
lbl.frame = CGRectMake(0, 15, cell.bounds.size.width - 10, 30);
lbl.textAlignment = UITextAlignmentCenter;
[label setText:#"Click to add new rower"];
break;
case 1:
UIImage *accessoryImage = [UIImage imageNamed:#"content_arrow.png"];
UIImageView *accessoryView = [[UIImageView alloc] initWithImage:accessoryImage];
cell.accessoryView = accessoryView;
[accessoryView release];
lbl.frame = CGRectMake(20, 15, cell.bounds.size.width - 10, 30);
lbl.textAlignment = UITextAlignmentLeft;
[lbl setText:[[[appDelegate rowersDataStore] objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:#"Name"]];
break;
}
return cell;
}