UIImageView in UITableViewCell repeat - ios

I have a bug.
I want to display a UIImageView on cells at special indexPath.row, but these UIImageView repeat while I scroll.
Exemple: I display my UIImageView on a cell indexPath.row == 0, if I scroll down, I see my UIImageView on the cell at indexPath.row == 8.
Here is my code:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [self getCellContentView:CellIdentifier];
}
UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1];
UIImageView *imgRead = (UIImageView *)[cell viewWithTag:6];
[cell.contentView insertSubview:imgRead aboveSubview:lblTemp1];
contentDictio = [dict objectAtIndex:indexPath.row];
lblTemp1.text = [contentDictio objectForKey:#"title"];
NSArray *paths_id = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath_id = ([paths_id count] > 0) ? [paths_id objectAtIndex:0] : nil;
NSString *path_id = [basePath_id stringByAppendingPathComponent:#"id.plist"];
NSMutableArray *mut_array_id = [[NSArray arrayWithContentsOfFile:path_id] mutableCopy];
NSMutableDictionary *c0 = [[NSMutableDictionary alloc] init];
NSString *idPlistData = [contentDictio objectForKey:#"id"];
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
}
else {
}
}
}
return cell;
}
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier {
CGRect Label1Frame = CGRectMake(kTableCellSmallMargin*2 + 60, kTableCellSmallMargin, 240, 25);
UILabel *lblTemp;
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier] autorelease];
//Initialize Label with tag 1.
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.tag = 1;
lblTemp.backgroundColor = [UIColor clearColor];
[lblTemp setFont: [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:15.0]];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
UIImageView *read=[[UIImageView alloc] initWithFrame:CGRectMake(kTableCellSmallMargin, kTableCellSmallMargin, 60, 60)];
read.backgroundColor=[UIColor clearColor];
read.tag = 6;
[cell.contentView addSubview:read];
[read release];
return cell;
}
Thanks...

The cell is cached, so you have to clear it when you want no image, like this:
BOOL found = NO;
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
found = YES;
}
else {
}
}
if (!found)
{
[imgRead setImage:nil];
}

Related

UITableView calling the another UITableView cellForRowAtIndexPath

I have two UIViewControllers with tableview. When the first cell loads in the second UIViewController it calls the cellForRowAtIndexPath in the same class but when it loads the second cell it calls the first viewControllers cellForRowAtIndexPath.
My code as follows:
SecondViewController:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NotificationsTableViewCell *cell = [self.notificationsTableView dequeueReusableCellWithIdentifier:#"NotificationCell"];
if(cell == nil)
{
cell = [[NotificationsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"NotificationCell"];
}
NSMutableDictionary *cellData = [self.databaseCall transactionFromDatabase:indexPath.row];
NSLog(#"%#", cellData);
cell.goalNameLabel.text = [cellData objectForKey:#"categoryName"];
NSString *cardTypeId = [cellData objectForKey:#"cardTypeId"];
NSString *tipsId = [cellData objectForKey:#"tipsId"];
if([self.defaultCardTypeId containsObject:cardTypeId])
{
NSUInteger index = [self.defaultCardTypeId indexOfObject:cardTypeId];
[self.defaultCardTypeId replaceObjectAtIndex:index withObject:cardTypeId];
}
else{
[self.defaultCardTypeId addObject:cardTypeId];
}
if([self.defaultTipId containsObject:tipsId])
{
NSUInteger index = [self.defaultCardTypeId indexOfObject:cardTypeId];
[self.defaultTipId replaceObjectAtIndex:index withObject:cardTypeId];
}
else{
[self.defaultTipId addObject:tipsId];
}
if([cardTypeId isEqualToString:#"1"])
{
UIImage *cellImage = [UIImage imageNamed:#"icon2.jpg"];
cell.cardTypeImage.image = cellImage;
cell.cardTypeLabel.text = #"GOOD TO KNOW";
cell.cardTypeLabel.textColor = [UIColor colorWithRed:252/255.0 green:171/255.0 blue:19/255.0 alpha:1];
}
if([cardTypeId isEqualToString:#"2"])
{
UIImage *cellImage = [UIImage imageNamed:#"icon1.jpg"];
cell.cardTypeImage.image = cellImage;
cell.cardTypeLabel.text = #"TO CONSIDER";
cell.cardTypeLabel.textColor = [UIColor colorWithRed:0/255.0 green:191/255.0 blue:243/255.0 alpha:1];
}
cell.notificationCard.layer.cornerRadius = 5;
// Configure the cell...
return cell;
}
FirstViewController:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
GoalsCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"GoalsListCell" forIndexPath:indexPath];
if(cell == nil)
{
cell = [[GoalsCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"GoalsListCell"];
}
NSInteger indexOfCategory = [self.databaseCall.arrColumnName indexOfObject:#"CategoryName"];
NSInteger indexOfImage = [self.databaseCall.arrColumnName indexOfObject:#"CategoryImage"];
NSInteger indexOfActive = [self.databaseCall.arrColumnName indexOfObject:#"coulmn"];
//Assigning the contents of cell
cell.goalName.text = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfCategory]];
NSString *categoryImage = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfImage]];
NSString *activeStatus = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfActive]];
UIImage *cellImage = [UIImage imageNamed:categoryImage];
cell.goalImage.image = cellImage;
[cell.favouriteButton addTarget:self action:#selector(favouriteButtonPressed:) forControlEvents:UIControlEventTouchDown];
NSMutableString *selectedRowImage = [[NSMutableString alloc] initWithString:#""];
//Checking whether the category is selected by user or not
if([activeStatus isEqualToString:#"yes"])
{
selectedRowImage = [NSMutableString stringWithFormat:#"starsel.png"];
}
else
{
selectedRowImage = [NSMutableString stringWithFormat:#"stardef.png"];
}
UIImage *favouriteIconImage = [UIImage imageNamed:selectedRowImage];
[cell.favouriteButton setBackgroundImage:favouriteIconImage forState:UIControlStateNormal];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
return cell;
}
Thanks in advance.
First of all i would say sorry for this stupid question.
The problem is due to the tableview datasource as specifies by #Paulw11, #Onik IV, #Kannan Vora. The secondViewController tableView has the datasource of firstViewController.

setAccessoryType destroys TableViewCell

I use a custom tablecell, labels and images are connected with tags.
If i add
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]
it destroys my tableview. the image destroys and the background-color.
here are the differences:
Does anyone have any idea where the problem could be?
Thanks
EDIT:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
if ([self labelCellNib]) {
[[self labelCellNib] instantiateWithOwner:self options:nil];
} else {
[[NSBundle mainBundle] loadNibNamed:#"LabelCell" owner:self options:nil];
}
cell = self.labelCell;
self.labelCell = nil;
}
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
dateFormatter = [[NSDateFormatter alloc] init];
static NSCalendar *calendar;
if(calendar == nil)
calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSString * timeStampString = [sqlTime objectAtIndex:indexPath.row];
NSTimeInterval _interval=[timeStampString doubleValue];
NSDate *createdAt = [NSDate dateWithTimeIntervalSince1970:_interval];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
// Datum in die Tabellen-Zelle einfügen
UILabel *label4 = (UILabel *)[cell viewWithTag:LABEL4];
label4.text = [NSString stringWithFormat:#"%#", [dateFormatter stringFromDate:createdAt]];
// Configure the cell...
UILabel *label1 = (UILabel *)[cell viewWithTag:LABEL1];
label1.text = [NSString stringWithFormat:#"%# %#", [sqlData objectAtIndex:indexPath.row], sonderzeichen];
UILabel *label2 = (UILabel *)[cell viewWithTag:LABEL2];
label2.text = [NSString stringWithFormat:#"Preis pro %#: %# €", sonderzeichen, [sqlPreis objectAtIndex:indexPath.row]];
UILabel *label3 = (UILabel *)[cell viewWithTag:LABEL3];
UIImageView *image = (UIImageView *)[cell viewWithTag:IMAGE_TAG];
if (indexPath.row==[itemsArray count]-1) {
image.image = [UIImage imageNamed:#"default.png"];
label3.text = #"-";
} else if ([itemsArray count]>1) {
int data_old = [[NSString stringWithFormat:#"%#", [sqlData objectAtIndex:indexPath.row]] intValue];
int data_new = [[NSString stringWithFormat:#"%#", [sqlData objectAtIndex:indexPath.row+1]] intValue];
label3.text = [NSString stringWithFormat:#"%i", data_old-data_new];
NSLog(#"%d -- %d", data_old, data_new);
if (data_new>data_old) {
image.image = [UIImage imageNamed:#"pfeil_runter.png"];
} else if (data_new<data_old) {
image.image = [UIImage imageNamed:#"pfeil_hoch.png"];
} else {
image.image = [UIImage imageNamed:#"minus.png"];
}
}
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
cell.contentView.backgroundColor = indexPath.row % 2? [UIColor colorWithRed:228.0/255.0 green:244.0/255.0 blue:199.0/255.0 alpha:1]:[UIColor whiteColor];
return cell;
}
You need to set the background color of the cell, rather than the contentView, but this doesn't work in cellForRowAtIndexPath. It needs to be in willDisplayCell:forRowAtIndexPath:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = indexPath.row % 2? [UIColor colorWithRed:228.0/255.0 green:244.0/255.0 blue:199.0/255.0 alpha:1]:[UIColor whiteColor];
}
As far as the images getting squashed, that has to do with the size of your subviews, and their constraints. I think you can fix those by giving width constraints to two of your labels (a pair over and under each other), but make their priority <1000, so when the accessory view is added, the width of those labels will get smaller. Also give the image view on the left a fixed width.

UITextField display issue in TableView cell

I created at least 10 cells with each UITextField on it, for registration page. When I insert the words on the textfield in the first cell, and when I scrolled the tableView, the textfield which is in another cell show up the word that I just typed.
Below is my code. The textField data which I input is looping, which is caused by dequeueReusableCellWithIdentifier... How can I solve this problem? Thank you very much.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"RCell";
RegisterCell *cell = (RegisterCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[[RegisterCell alloc] initWithFrame:CGRectMake(0, 0, 280, 44) reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.section == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
UITextField *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.row == 0)
{
valTxtField.text = #"";
emailTxtFld = valTxtField; //emailTxtFld is global variable
}
if(indexPath.row == 1)
{
valTxtField.text = #"";
reEmailTxtFld = valTxtField; //reEmailTxtFld is global variable
}
[cell.contentView addSubview:valTxtField];
[valTxtField release];
}
else if(indexPath.section == 1){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+10];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
else if(indexPath.section == 2){
if(indexPath.row == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+11];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
}
return cell;
}
An easy way is to just remove all subviews from the cells contentView before you add subviews, example:
for (UIView *subview in [cell.contentView subviews])
[subview removeFromSuperview];
A more efficient way would be to do all the creation of cells inside the if (cell == nil) statement, but that depends on how many cells you have in the table.
The right implementation is to move the creation of any view whithin if (cell == nil)
Like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"RCell";
RegisterCell *cell = (RegisterCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField *valTxtField;
if (cell == nil)
{
cell = [[[RegisterCell alloc] initWithFrame:CGRectMake(0, 0, 280, 44) reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.section == 0){
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;
valTxtField.tag = 100;
[cell.contentView addSubview:valTxtField];
[valTxtField release];
}
}
valTxtField = (UITextField *)[cell.contentView viewWithTag:100];
if(indexPath.section == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
if(indexPath.row == 0)
{
valTxtField.text = #"";
emailTxtFld = valTxtField; //emailTxtFld is global variable
}
if(indexPath.row == 1)
{
valTxtField.text = #"";
reEmailTxtFld = valTxtField; //reEmailTxtFld is global variable
}
}
else if(indexPath.section == 1){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+10];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
else if(indexPath.section == 2){
if(indexPath.row == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+11];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
}
return cell;

Custom subviews on UITableViewCell and scrolling issue

I would like to get some suggesstions about the code shown below. The scrolling is kind of slow on iPhone, but not on simulator. What I am trying to do is to show multiple hours and messages on each row and each row may have different numbers of hours and messages.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// message + hours
static NSString *CellIdentifier = #"Cell1";
// others
static NSString *CellIdentifier1 = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
UILabel *hoursLabel;
UILabel *infoLabel;
UILabel *dayLabel;
switch (indexPath.section) {
case 0:
cell1 = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
if ([hoursArray count] > 0 && [infoArray count] > 0) {
harray = [self seperateString:[hoursArray objectAtIndex:indexPath.row]];
iarray = [self seperateString:[infoArray objectAtIndex:indexPath.row]];
// check how many hours in an array
int loop = [harray count];
int currentInfoHeight = 0;
int currentHourHeight = 0;
int labelHeight = 0;
for (int i = 0; i < loop ; i++) {
NSString *Text = [[NSString alloc] initWithFormat:#"%#", [harray objectAtIndex:i]];
NSString *Text1 = [[NSString alloc] initWithFormat:#"%#", [iarray objectAtIndex:i]];
UIFont *cellFont = [UIFont systemFontOfSize:hourfontSize];
UIFont *cellFont1 = [UIFont systemFontOfSize:messageFontSize];
CGSize constraintSize = CGSizeMake(180.0f, MAXFLOAT);
CGSize labelSize = [Text sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
CGSize labelSize1 = [Text1 sizeWithFont:cellFont1 constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
/* HourLabel */
hoursLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
70.0 + 2.0 * cell1.indentationWidth,
currentHourHeight + gap,
tableView.bounds.size.width - 70.0 - 4.0 * cell1.indentationWidth,
labelSize.height)]
autorelease];
hoursLabel.text = [NSString stringWithFormat:[harray objectAtIndex:i]];
hoursLabel.backgroundColor = [UIColor clearColor];
hoursLabel.textColor = [UIColor blackColor];
// hoursLabel.shadowColor = [UIColor blackColor];
// hoursLabel.shadowOffset = CGSizeMake(0, 1);
hoursLabel.font = [UIFont systemFontOfSize:hourfontSize];
[cell1.contentView addSubview:hoursLabel];
if (![[iarray objectAtIndex:i] isEqualToString:#"-"]) {
/* infoLabel */
infoLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
70.0 + 2.0 * cell1.indentationWidth,
currentInfoHeight + gap + labelSize.height,
tableView.bounds.size.width - 70.0 - 4.0 * cell1.indentationWidth,
labelSize1.height)]
autorelease];
infoLabel.text = [NSString stringWithFormat:[iarray objectAtIndex:i]];
infoLabel.numberOfLines = 0;
infoLabel.backgroundColor = [UIColor clearColor];
infoLabel.textColor = [UIColor colorWithRed:51.0/255 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];
infoLabel.font = [UIFont systemFontOfSize:messageFontSize];
[cell1.contentView addSubview:infoLabel];
labelHeight = (infoLabel.bounds.size.height);
}
else
{
labelHeight=0;
}
/* store current height of label */
currentHourHeight = (hoursLabel.bounds.size.height) + labelHeight + gap + currentHourHeight;
currentInfoHeight = (hoursLabel.bounds.size.height) + labelHeight + gap + currentInfoHeight;
}
}
/* dayLabel */
dayLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
2.0 * cell1.indentationWidth,
[self tableView:tableView_ heightForRowAtIndexPath:indexPath] / 2.0f - dayFontSize/2 ,
tableView.bounds.size.width -
70.0 - 4.0 * cell1.indentationWidth,
dayFontSize)]
autorelease];
[cell1.contentView addSubview:dayLabel];
/* Configure the properties for the text that are the same on every row */
dayLabel.backgroundColor = [UIColor clearColor];
dayLabel.textColor = [UIColor colorWithRed:207.0/255 green:181.0/255.0 blue:59.0/255.0 alpha:1.0];
dayLabel.font = [UIFont boldSystemFontOfSize:dayFontSize];
/* Draw a line to divide info and message into two sections */
UIView *lineView = [[[UIView alloc] initWithFrame:CGRectMake(79, 0, 1.5, cell1.contentView.bounds.size.height)] autorelease];
lineView.backgroundColor = [self.tableView_ separatorColor];
lineView.autoresizingMask = 0x3f;
[cell1.contentView addSubview:lineView];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"EEE"];
dayLabel.text = [NSString stringWithFormat:[daysArray objectAtIndex:[indexPath row]]];
[cell1 setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell1;
case 1:
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = #"View information for this location";
cell.textLabel.font = [UIFont systemFontOfSize:16];
cell.textLabel.textAlignment = UITextAlignmentCenter;
return cell;
case 2:
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = #"Show building on campus map";
cell.textLabel.font = [UIFont systemFontOfSize:16];
cell.textLabel.textAlignment = UITextAlignmentCenter;
return cell;
case 3:
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = #"Direction to building";
cell.textLabel.font = [UIFont systemFontOfSize:16];
cell.textLabel.textAlignment = UITextAlignmentCenter;
return cell;
default:
break;
}
return cell;
}
You are allocating a NSDateFormatter for each cell. In my experience NSDateFormatter allocation and configuration are some of the most expensive calls available. They take significant amount of time.
Make that NSDateFormatter an instance variable so you have to allocate and configure it exactly one time.
you are not reusing your cells. If you don't reuse your cells your performance will suffer.
The pattern to reuse is something like this:
.
- (NSDateFormatter *)weekDayDateFormatter {
if (!myWeekDayDateFormatter) {
myWeekDayDateFormatter = [[NSDateFormatter alloc] init];
[myWeekDayDateFormatter setDateFormat:#"EEE"];
}
return myWeekDayDateFormatter;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSInteger secondLabelTag = 1001;
static NSInteger imageViewTag = 1002;
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
UITableViewCell *cell = nil;
switch (indexPath.section) {
case 0: {
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier1];
// allocate subviews and configure properties that never change
UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectZero];
secondLabel.tag = secondLabelTag;
secondLabel.textColor = [UIColor orangeColor];
[cell.contentView addSubview:secondLabel];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
imageView.tag = imageViewTag;
imageView.contentMode = UIViewContentModeScaleAspectFill;
[cell.contentView addSubview:imageView];
}
// Whatever happened before you have a valid cell here
UILabel *secondLabel = (UILabel *)[cell.contentView viewWithTag:secondLabelTag];
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:imageViewTag];
secondLabel.text = [self.weekDayDateFormatter stringFromDate:[dataSource objectAtIndex:indexPath.row]];
imageView.image = [dataSource objectAtIndex:indexPath.row];
break;
}
case 1: {
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
// configure properties that never change between cells
cell.textLabel.textColor = [UIColor greenColor];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// configure properties that are different between cells
cell.textLabel.text = [dataSource objectAtIndex:indexPath.row];
cell.textLabel.backgroundColor = [dataSource objectAtIndex:indexPath.row];
break;
}
}
The code in the tableView:cellForRowAtIndexPath: parts that are called every time should execute as fast as possible. During scrolling this method is called for every single cell.
I guess, the performance isn't lost here, but in -cellForRowAtIndexPath:
Do you use – prepareForReuse / – dequeueReusableCellWithIdentifier:?

Section on top of section iphone table

I am building a sectioned table, and it is showing up with what looks to be a section on top of a section. You can see on the image that there is a white line under each section.
The image
Here is the code I have to build the table:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [alertList count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier;
if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)
{
CellIdentifier = #"CellLandscape";
}
else
{
CellIdentifier = #"Cell";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier]
autorelease];
//cell.contentView.backgroundColor = [UIColor blackColor];
CGRect frame;
if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)
{
frame.origin.x = 370;
//titleFrame.size.width = 320;
}
else
{
frame.origin.x = 220;
//titleFrame.size.width = 220;
}
frame.origin.y = 5;
frame.size.height = 15;
frame.size.width = 74;
UILabel *instLabel = [[UILabel alloc] initWithFrame:frame];
instLabel.tag = 1;
[cell.contentView addSubview:instLabel];
[instLabel release];
}
// Configure the cell.
Alert *p = [alertList objectAtIndex:indexPath.section];
UILabel *instLabel = (UILabel *) [cell.contentView viewWithTag:1];
instLabel.text = [p docDate];
instLabel.textColor = [UIColor blackColor];
[instLabel setFont:[UIFont fontWithName:#"Arial" size:12]];
NSString *path;
if ([[p subscription] isEqual:#"Y"])
{
path = [[NSBundle mainBundle] pathForResource:#"watchlist_on" ofType:#"png"];
}
else
{
path = [[NSBundle mainBundle] pathForResource:#"watchlist_off" ofType:#"png"];
}
//NSLog(#"%#", path);
cell.textLabel.textColor = [UIColor colorWithRed:.847 green:0 blue: 0 alpha: 1];
[cell.textLabel setFont:[UIFont boldSystemFontOfSize:13]];
cell.textLabel.text = [[NSString alloc] initWithFormat:#"%#", [p Name]];
cell.detailTextLabel.textColor = [UIColor blackColor];
[cell.detailTextLabel setFont:[UIFont fontWithName:#"Arial" size: 10]];
cell.detailTextLabel.text = [p docTitle];
cell.detailTextLabel.textColor = [UIColor blackColor];
[cell.detailTextLabel setFont:[UIFont fontWithName:#"Arial" size: 10]];
//cell.detailTextLabel.text = [p docDate];
//cell.imageView.image = [UIImage imageWithContentsOfFile:path];
cell.imageView.userInteractionEnabled = YES;
cell.imageView.userInteractionEnabled = YES;
//cell.imageView.image = [UIImage imageWithContentsOfFile:path];
/// [cell addSubview:imgView];
//cell.textLabel.text = [[NSString alloc] initWithFormat:#"%#, %# G: %#\nDOB: %# Inst: %#", [p lastName], [p firstName], [p gender],
// [p birthDate], [p inst]];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
//only 1 alert at a time
//make doc list from alert object
Document *documentList1 = [[Document alloc] init];
self.documentList = documentList1;
[documentList1 setTitle:[p docTitle]];
[documentList1 setUniqueId:[p uniqueId]];
[documentList1 setDate:[p docDate]];
[documentList1 setRepoOID:[p repoOid]];
[documentArray addObject:documentList];
return cell;
}
Change the table view's separator style to either single line or none - you probably have it on single line etched.

Resources