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:?
Related
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];
}
I want to parse xml and show the title, description and image in table cell.
I did following code, but if image is not available, then also garbage image is displaying on cell.
I did code to hide it but image view not hiding.
Also I set frame to zero values but image view with garbage image is displaying:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
appDelegate = (AppDelegate_iPhone *) [[UIApplication sharedApplication] delegate];
if (section == 0) {
return [appDelegate.TrendDataArray count];
}else {
return [appDelegate.MyDataArray count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(section == 0)
return #" Trending ";
else
return #" Live Feeds ";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *lblTitle;
UILabel *lbldescription;
UIImageView *imgViewTemp;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
lblTitle = [[UILabel alloc] initWithFrame:CGRectZero];
[lblTitle setLineBreakMode:UILineBreakModeWordWrap];
[lblTitle setNumberOfLines:2];
lblTitle.textAlignment= UITextAlignmentLeft;
[lblTitle setFont:[UIFont fontWithName:#"Helvetica-Bold" size:FONT]];
lblTitle.textColor=[UIColor blackColor];
[lblTitle setTag:1];
lbldescription = [[UILabel alloc] initWithFrame:CGRectZero];
[lbldescription setLineBreakMode:UILineBreakModeWordWrap];
[lbldescription setNumberOfLines:3];
lbldescription.textAlignment= UITextAlignmentLeft;
[lbldescription setFont:[UIFont fontWithName:#"Helvetica" size:FONT2]];
lbldescription.textColor=[UIColor grayColor];
[lbldescription sizeToFit];
[lbldescription setTag:2];
imgViewTemp = [[UIImageView alloc] initWithFrame:CGRectZero];
[imgViewTemp setTag:3];
[cell.contentView addSubview:lblTitle];
[cell.contentView addSubview:lbldescription];
//[imgViewTemp release];
[lblTitle release];
[lbldescription release];
}
// Configure the cell...
if (indexPath.section == 0) {
appDelegate=(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
objXmlParse_Attributes= [appDelegate.TrendDataArray objectAtIndex:indexPath.row];
}else if (indexPath.section == 1) {
appDelegate=(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
objXmlParse_Attributes= [appDelegate.MyDataArray objectAtIndex:indexPath.row];
}
NSString *text = objXmlParse_Attributes.CommenUrlTitle;
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *text2 = objXmlParse_Attributes.CommenUrlDescription;
text2 = [text2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
CGSize constraint = CGSizeMake(WIDTH - (MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont fontWithName:#"Helvetica-Bold" size:FONT] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGSize size2 = [text2 sizeWithFont:[UIFont fontWithName:#"Helvetica" size:FONT2] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
NSString *link = [NSString stringWithFormat:#"%#", objXmlParse_Attributes.CommenUrlImage];
//imgViewTemp = [[UIImageView alloc] initWithFrame:CGRectZero];
//[UIImage imageNamed:#"noimage.png"]
if([link isEqualToString:#"No image"] || [link isEqualToString:#"no image"]){
link = #"";
if ([link isEqualToString:#""]) {
imgViewTemp = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,0,0)];
//[imgViewTemp release];
lblTitle = (UILabel*)[cell.contentView viewWithTag:1];
[lblTitle setText:text];
[lblTitle setFrame:CGRectMake(MARGIN+3,MARGIN, WIDTH-110+83,MIN(size.height,30))];
lbldescription = (UILabel*)[cell.contentView viewWithTag:2];
[lbldescription setText:text2];
[lbldescription setFrame:CGRectMake(MARGIN+3,MARGIN + MIN(size.height,30),WIDTH-110+83,MIN(size2.height,40))];
}
}
else{
//imgViewTemp = (UIImageView*)[cell.contentView viewWithTag:3];
imgViewTemp = [[UIImageView alloc] initWithFrame:CGRectMake(7,11,73,60)];
[imgViewTemp setImageWithURL:[NSURL URLWithString:link] placeholderImage:nil];
//image1.hidden=FALSE;
lblTitle = (UILabel*)[cell.contentView viewWithTag:1];
[lblTitle setText:text];
[lblTitle setFrame:CGRectMake(MARGIN + 83, MARGIN, WIDTH-110,MIN(size.height,30))];
lbldescription = (UILabel*)[cell.contentView viewWithTag:2];
[lbldescription setText:text2];
[lbldescription setFrame:CGRectMake(MARGIN + 83, MARGIN + MIN(size.height,30),WIDTH-110,MIN(size2.height,40))];
[cell.contentView addSubview:imgViewTemp];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
Hey just search for tutorial to make table. Dont ask such query in this portion, there is a lot of example for UITableView...I hope you understand.
Why tableview data are overlapping? i have attached my code.
If i explain my code again then
xml data are in records array which are displaying in tableview.
First time when program execute then data are in right place but when i start scroll vertically the data start to display in various cell.suppose first cell shows in last cell,second cell data shows in first cell.....so on.
NOTE THAT: For overlapping problem i also used switch and viewwithtag but still now tableview data start to display in wrong cell when i start scrolling on UITableview.
// 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 = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSLog(#"%d",indexPath.section);
switch (indexPath.section) {
case 0:
order_cellView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, cell.frame.size.width,cell.frame.size.height) ];
order_cellView.backgroundColor = [UIColor redColor];
order_cellView.tag =1000;
NSLog(#"index path 0");
CGRect frame;
frame.origin.x =0;
frame.origin.y = 10;
frame.size.height = 30;
frame.size.width = 230;
CGRect valueFrame;
valueFrame.origin.x =237;
valueFrame.origin.y = 5;
valueFrame.size.height = 30;
valueFrame.size.width = 80;
for(int m=0;m<numberOfProduct;m++){
NSLog(#"for loop here");
productLabel = [[UILabel alloc] initWithFrame:frame];
productLabel.tag = m;
productLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
productLabel.backgroundColor = [UIColor clearColor];
productLabel.lineBreakMode = UILineBreakModeCharacterWrap;
productLabel.numberOfLines = 2;
productLabel.textAlignment = UITextAlignmentCenter;
[order_cellView addSubview:productLabel];
productLabel.text = [NSString stringWithFormat:#"%# x %# x %#",[[products objectAtIndex:m] objectAtIndex:1],[[products objectAtIndex:m] objectAtIndex:2],[[products objectAtIndex:m] objectAtIndex:3]];
frame.origin.y += 45;
productValueLabel = [[UILabel alloc] initWithFrame:valueFrame];
productValueLabel.tag = m+2;
productValueLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
productValueLabel.backgroundColor = [UIColor clearColor];
productValueLabel.lineBreakMode = UILineBreakModeCharacterWrap;
productValueLabel.numberOfLines = 2;
productValueLabel.textAlignment = UITextAlignmentCenter;
productValueLabel.text = [NSString stringWithFormat:#"%#",[[products objectAtIndex:m] objectAtIndex:5]];
[order_cellView addSubview:productValueLabel];
valueFrame.origin.y += 45;
}
[cell.contentView addSubview:order_cellView];
break;
case 1:
email_cellView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, cell.frame.size.width,cell.frame.size.height) ];
email_cellView.backgroundColor = [UIColor clearColor];
email_cellView.tag =1001;
emailAdressLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, cell.frame.size.width, cell.frame.size.height)];
emailAdressLabel.tag = 100;
emailAdressLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
emailAdressLabel.backgroundColor = [UIColor clearColor];
emailAdressLabel.lineBreakMode = UILineBreakModeCharacterWrap;
emailAdressLabel.numberOfLines = 2;
emailAdressLabel.textAlignment = UITextAlignmentLeft;
emailAdressLabel.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:6]];
[email_cellView addSubview:emailAdressLabel];
[cell.contentView addSubview:email_cellView];
break;
case 2:
phoneNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, cell.frame.size.width, cell.frame.size.height)];
phoneNumberLabel.tag = 101;
phoneNumberLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
phoneNumberLabel.backgroundColor = [UIColor clearColor];
phoneNumberLabel.lineBreakMode = UILineBreakModeCharacterWrap;
phoneNumberLabel.numberOfLines = 1;
phoneNumberLabel.textAlignment = UITextAlignmentLeft;
phoneNumberLabel.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:7]];
[cell.contentView addSubview:phoneNumberLabel];
break;
case 3:
billingDetails = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 160, cell.frame.size.height)];
billingDetails.tag = 102;
billingDetails.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
billingDetails.backgroundColor = [UIColor clearColor];
billingDetails.lineBreakMode = UILineBreakModeCharacterWrap;
billingDetails.numberOfLines = 4;
billingDetails.textAlignment = UITextAlignmentLeft;
billingDetails.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:4]];
[cell.contentView addSubview:billingDetails];
break;
case 4:
shippingDetails = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 160, cell.frame.size.height)];
shippingDetails.tag = 103;
shippingDetails.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
shippingDetails.backgroundColor = [UIColor clearColor];
shippingDetails.lineBreakMode = UILineBreakModeCharacterWrap;
shippingDetails.numberOfLines = 4;
shippingDetails.textAlignment = UITextAlignmentLeft;
shippingDetails.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:5]];
[cell.contentView addSubview:shippingDetails];
break;
case 5:
orderStatus = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, cell.frame.size.width, cell.frame.size.height)];
orderStatus.tag = 104;
orderStatus.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
orderStatus.backgroundColor = [UIColor clearColor];
orderStatus.lineBreakMode = UILineBreakModeCharacterWrap;
orderStatus.numberOfLines = 1;
orderStatus.textAlignment = UITextAlignmentLeft;
orderStatus.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:19]];
[cell.contentView addSubview:orderStatus];
break;
case 6:
deleteOrder = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, cell.frame.size.width, cell.frame.size.height)];
deleteOrder.tag = 110;
deleteOrder.font = [UIFont fontWithName:#"Arial-BoldMT" size:13];
deleteOrder.backgroundColor = [UIColor clearColor];
deleteOrder.lineBreakMode = UILineBreakModeCharacterWrap;
deleteOrder.numberOfLines = 1;
deleteOrder.textAlignment = UITextAlignmentLeft;
deleteOrder.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:19]];
[cell.contentView addSubview:deleteOrder];
break;
default:
break;
}
}
switch (indexPath.section) {
case 0:
order_cellView = (UIView *)[cell.contentView viewWithTag:1000];
for(int m=0;m<numberOfProduct;m++){
productLabel = (UILabel *)[order_cellView viewWithTag:m];
productValueLabel = (UILabel *)[order_cellView viewWithTag:m+2];
}
if(indexPath.section == 0){
for(int m=0;m<numberOfProduct;m++){
productLabel.text = [NSString stringWithFormat:#"%# x %# x %#",[[products objectAtIndex:m] objectAtIndex:1],[[products objectAtIndex:m] objectAtIndex:2],[[products objectAtIndex:m] objectAtIndex:3]];
productValueLabel.text = [NSString stringWithFormat:#"%#",[[products objectAtIndex:m] objectAtIndex:5]];
}
}
break;
case 1:
email_cellView = (UIView *)[cell.contentView viewWithTag:1001];
emailAdressLabel = (UILabel *)[email_cellView viewWithTag:100];
emailAdressLabel.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:6]];
break;
case 2:
phoneNumberLabel = (UILabel *)[cell.contentView viewWithTag:101];
phoneNumberLabel.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:7]];
break;
case 3:
billingDetails = (UILabel *)[cell.contentView viewWithTag:102];
billingDetails.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:4]];
break;
case 4:
shippingDetails = (UILabel *)[cell.contentView viewWithTag:103];
shippingDetails.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:5]];
break;
case 5:
orderStatus = (UILabel *)[cell.contentView viewWithTag:104];
orderStatus.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:19]];
break;
case 6:
deleteOrder = (UILabel *)[cell.contentView viewWithTag:110];
deleteOrder.text = [NSString stringWithFormat:#"%#",[[records objectAtIndex:0] objectAtIndex:19]];
break;
default:
break;
}
return cell;
}
I think your main problem is that you have seven different "types" of cell but only one "reuse identifier." This means that an order cell could be later reused as a delete order cell. However, when reused, the cell won't necessarily have all the elements it needs to display fully.
For example, email cell has a tag of 1001 and delete cell has a tag of 110, but not vice-versa.
just needs to give different identifier for each cell you are declaring so if you will do that they will identify the cell and data will not merge on each other
and one more sol is to give each cell subview tag and view the cell with subviews tag..
replace CellIdentifier with nil-
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
It is because you are reusing the cell identifier so data is overlapping
I have a NSMutableArray named as records and a NSArray.
Now I am retrieving an XML attribute and its value, using TBXML parser and inserting the attribute value in the NSArray.
This NSArray is an object of records.
What will be the numerberOfRowsInSection when I want to display the value of XML data in tableview cell?
This is my data retrieving procedure....
[records addObject:[NSArray arrayWithObjects:
[TBXML textForElement:id],
[TBXML textForElement:productNumber],
[TBXML textForElement:name],
[TBXML textForElement:availableStock],
[TBXML textForElement:image],
[TBXML textForElement:quantityOrderMin],
[TBXML textForElement:dateCreated],
[TBXML textForElement:dateUpdated],nil]];
And my XML data are....
<ProductData HASH="21106941">
<id>1</id>
<productNumber>a91cc0f4c7</productNumber>
<name>Product 1</name>
<seoTitle>product-1</seoTitle>
<viewCount>0</viewCount>
<availableStock>100.0</availableStock>
<lowStock>0.0</lowStock>
<image>5e928bbae358c93caedf6115fa7d178b.jpg</image>
<quantityOrderMax>20.0</quantityOrderMax>
<dateCreated>2011-10-06T16:08:45</dateCreated>
</ProductData>
<ProductData HASH="409555632">
<id>2</id>
<productNumber>d8287e2e51</productNumber>
<name>Product 2</name>
<seoTitle>product-2</seoTitle>
<description>
<p>Lorem ipsum dolor sit amet, consectetue...</p>
</description>
<viewCount>0</viewCount>
<availableStock>100.0</availableStock>
<image>8bbd8dfff3cdd28285d07810a4fe7c32.jpg</image>
<quantityOrderMin>1.0</quantityOrderMin>
<dateCreated>2011-10-06T16:08:45</dateCreated>
</ProductData>
I am being able to retrieve data in UITableviewCell, but it's displaying first two retrieved data of the NSArray because the number of rows are two in records array. but i want to set the numberOfRowsInsection will be according to the total number of attribute value retrieved by NSArray.
I have got the problem and I know the problem is here:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"The number of row in the object array: %d ",[records count]);
return [records count];
}
How can I fix it?
#pragma mark tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
int sectionCount = [records count];
NSLog(#"section cout: %d",sectionCount);
return sectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
cell.accessoryType = UITableViewCellSelectionStyleNone;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
cellView = [[[UIView alloc] initWithFrame:CGRectMake(5,8,290, 120)] autorelease];
cellView.backgroundColor = [UIColor clearColor];
cellView.tag =10;
[cell.contentView addSubview:cellView];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 40, 48, 48)];
imgView.image = [UIImage imageNamed:#"productbox.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 2.0;
imgView.tag = 5;
[cellView addSubview:imgView];
CGRect idLabelRect = CGRectMake(65, 0, 190, 18);
idLabel = [[[UILabel alloc] initWithFrame:idLabelRect] autorelease];
idLabel.textAlignment = UITextAlignmentLeft;
idLabel.textColor = [UIColor blackColor];
idLabel.font = [UIFont systemFontOfSize:12];
idLabel.backgroundColor = [UIColor clearColor];
idLabel.layer.borderColor = [UIColor grayColor].CGColor;
idLabel.tag = 0;
CGRect statusRect = CGRectMake(65, 22, 190, 22);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.layer.borderColor = [UIColor grayColor].CGColor;
statusLabel.tag = 1;
CGRect orderDateRect = CGRectMake(65, 48, 190, 22);
orderDate = [[[UILabel alloc] initWithFrame:orderDateRect] autorelease];
orderDate.textAlignment = UITextAlignmentLeft;
orderDate.textColor = [UIColor blackColor];
orderDate.font = [UIFont systemFontOfSize:12];
orderDate.backgroundColor = [UIColor clearColor];
orderDate.layer.borderColor = [UIColor grayColor].CGColor;
orderDate.tag = 2;
CGRect byRect = CGRectMake(65, 75, 190, 22);
byLabel = [[[UILabel alloc] initWithFrame:byRect] autorelease];
byLabel.textAlignment = UITextAlignmentLeft;
byLabel.textColor = [UIColor blackColor];
byLabel.font = [UIFont systemFontOfSize:12];
byLabel.backgroundColor = [UIColor clearColor];
byLabel.layer.borderColor = [UIColor grayColor].CGColor;
byLabel.tag = 3;
CGRect totalRect = CGRectMake(65, 98, 190, 22);
totalLabel = [[[UILabel alloc] initWithFrame:totalRect] autorelease];
totalLabel.textAlignment = UITextAlignmentLeft;
totalLabel.textColor = [UIColor blackColor];
totalLabel.font = [UIFont systemFontOfSize:12];
totalLabel.backgroundColor = [UIColor clearColor];
totalLabel.layer.borderColor = [UIColor grayColor].CGColor;
totalLabel.tag = 4;
[cellView addSubview:idLabel];
[cellView addSubview:statusLabel];
[cellView addSubview:orderDate];
[cellView addSubview:byLabel];
[cellView addSubview:totalLabel];
}
cellView = (UIView *)[cell.contentView viewWithTag:10];
idLabel = (UILabel *)[cellView viewWithTag:0];
statusLabel = (UILabel *)[cellView viewWithTag:1];
orderDate = (UILabel *)[cellView viewWithTag:2];
byLabel = (UILabel *)[cellView viewWithTag:3];
totalLabel = (UILabel *)[cellView viewWithTag:4];
imgView = (UIImageView *)[cellView viewWithTag:5];
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:4]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//Get the selected country
NSString *selectedSection = [ NSString stringWithFormat:#"%#",[[records objectAtIndex:indexPath.section] objectAtIndex:0] ];
dvController = [[OrderDetailsViewController alloc] initWithNibNameAndCurrentTweetUser:#"OrderDetailsViewController" bundle:nil:selectedSection];
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
dvController = nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 130;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)];
[v setBackgroundColor:[UIColor blackColor]];
UILabel* hdr = [[[UILabel alloc] initWithFrame:CGRectMake(10,0, tableView.bounds.size.width,20)] autorelease];
hdr.textAlignment = UITextAlignmentLeft;
hdr.font = [UIFont fontWithName:#"Arial-BoldMT" size:12];
hdr.textColor = [UIColor whiteColor];
hdr.backgroundColor = [UIColor blackColor];
[v addSubview:hdr];
hdr.text = [NSString stringWithFormat:#"Order #%#",[[records objectAtIndex:section] objectAtIndex:0]];
return v;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 20;
}
There are two ways to approach this problem.
The right way would be to take a look at this TBXML tutorial regarding parsing. This shows you what to do to parse each of the attributes out of each ProductData element entry.
The brute force method (which isn't one that I would do) would be to parse through your "records" array, which looks like this:
#"<id>1</id>",#"<productNumber>a91cc0f4c7</productNumber>",#"<name>Product 1</name>",#"<seoTitle>product-1</seoTitle>",#"<viewCount>0</viewCount>",
#"<availableStock>100.0</availableStock>",#"<lowStock>0.0</lowStock>",#"<image>5e928bbae358c93caedf6115fa7d178b.jpg</image>",
#"<basePrice>10.0</basePrice>",#"<costPrice>0.0</costPrice>",#"<height>1.0</height>",#"<width>1.0</width>",#"<depth>1.0</depth>",#"<weight>2.0</weight>"
and so on via this fast enumeration
for(NSString * elementText in records)
{
NSLog( #"%#", elementText );
// and search for "<" and ">" and strip out the name and the value using
// substring
}
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.