UITableViewCell scroll not smooth with custom cell - ios

This is the cellForRowAtIndexPath :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MessageDetailCell *cell;
#try {
if(indexPath != nil && indexPath.row < arrMessages.count)
{
cell = [tableView dequeueReusableCellWithIdentifier:#"MessageDetailCell"];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MessageDetailCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
if ([cell respondsToSelector:#selector(layoutMargins)]) {
cell.layoutMargins = UIEdgeInsetsZero;
cell.preservesSuperviewLayoutMargins = false;
}
}
else
{
NSArray *arr = [cell.contentView subviews];
for(int i=0; i<[arr count]; i++)
{
UIView *view = [arr objectAtIndex:i];
[view removeFromSuperview];
}
}
cell.tag = indexPath.row;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
MessageThread *thread = [arrMessages objectAtIndex:indexPath.row];
float xAxis = 10.0;
float yAxis = 10.0;
float imageDimention = 40;
float fontSize = 20;
NSLog(#"");
if(indexPath.row == 0)
{
xAxis = 10;
imageDimention = 40;
fontSize = 20;
cell.imgUserWidthConstraint.constant = 40;
cell.imgUserHeightConstraint.constant = 40;
cell.lblContentLeftConstraint.constant = 64;
cell.btnReplyLeftConstraint.constant = 64;
}
else
{
xAxis = 32 * thread.ReplyLevel;
imageDimention = 32;
fontSize = 17;
cell.imgUserWidthConstraint.constant = 32;
cell.imgUserHeightConstraint.constant = 32;
cell.lblContentLeftConstraint.constant = 110;
cell.btnReplyLeftConstraint.constant = 110;
}
if(![thread.sender.Image isEqual:#""] && ![thread.sender.Image.lowercaseString containsString:#"default"])
[self createImage:CGRectMake(xAxis, yAxis, imageDimention, imageDimention) cell:cell messageThread:thread];
else
{
UILabel *lblLetter = [[UILabel alloc]initWithFrame:CGRectMake(xAxis, yAxis, imageDimention, imageDimention)];
lblLetter.layer.cornerRadius = lblLetter.frame.size.width / 2;
lblLetter.layer.borderColor = [[UIColor blackColor] CGColor];
lblLetter.layer.borderWidth = 0.8;
lblLetter.layer.masksToBounds = YES;
lblLetter.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0];
lblLetter.text = [thread.sender.FirstName substringToIndex:1];
lblLetter.font = [UIFont boldSystemFontOfSize:fontSize];
lblLetter.textAlignment = NSTextAlignmentCenter;
lblLetter.textColor = [UIColor blackColor];
[cell.contentView addSubview:lblLetter];
}
cell.imgUserLeftConstraint.constant = xAxis;
xAxis = 80;
NSString *recipients = #"";
for(Recipient *rp in thread.Recipients)
{
recipients = [recipients stringByAppendingString:[NSString stringWithFormat:#"%#, ", rp.Name]];
}
recipients = [recipients substringToIndex:recipients.length - 2];
NSAttributedString * attrUserText;
attrUserText = [[NSAttributedString alloc] initWithData:[[NSString stringWithFormat:#"%# → %#", thread.sender.FullName, recipients] dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSAttributedString *attrArrow = [[NSAttributedString alloc] initWithData:[[NSString stringWithFormat:#" → %#", recipients] dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithAttributedString:attrUserText];
int firstHalf = (int)thread.sender.FullName.length;
int secondHalf = (int)attrArrow.length;
[string addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(firstHalf,secondHalf + 1)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,firstHalf)];
cell.lblUsers.attributedText = string;
cell.lblUsers.textAlignment = NSTextAlignmentLeft;
cell.lblUsers.font = [UIFont boldSystemFontOfSize:15];
cell.lblUsers.numberOfLines = 0;
cell.lblDate.text = [self returnDate:thread.CreatedOn];
cell.lblDateTopConstraint.constant = 10;
cell.lblDate.textAlignment = NSTextAlignmentLeft;
cell.lblDate.font = [UIFont systemFontOfSize:12];
cell.lblContent.tag = (int)indexPath.row;
cell.lblContent.backgroundColor = [UIColor clearColor];
cell.lblContent.textColor = [UIColor blackColor];
cell.lblContent.textAlignment = NSTextAlignmentLeft;
cell.lblContent.font = [UIFont systemFontOfSize:14];
cell.lblContent.text = thread.MessageContent;
cell.lblContent.dataDetectorTypes = UIDataDetectorTypeLink;
cell.lblContent.dataDetectorTypes = UIDataDetectorTypeAll;
cell.lblContent.scrollEnabled = NO;
cell.lblContent.editable = NO;
cell.lblContent.selectable = YES;
cell.lblContent.contentInset = UIEdgeInsetsMake(0, -4, 0, 0);
[cell.lblContent layoutIfNeeded];
//
yAxis = yAxis + 30;
float yAxisDocAttachment = 0;
cell.viewAttachmentHeightConstraint.constant = 0;
BOOL isDoc = NO;
BOOL isImage = NO;
if(thread.attachments.count > 0)
{
for(MessageAttachment *msgDoc in thread.attachments)
{
if(![msgDoc.Type isEqual:#"Image"])
{
isDoc = YES;
cell.viewAttachmentCollection.hidden = NO;
cell.viewAttachmentTopConstraint.constant = 10;
if((int)indexPath.row != 0)
cell.viewAttachmentLeftConstraint.constant = xAxis - 16;
else
cell.viewAttachmentLeftConstraint.constant = xAxis;
UIView *viewAttachment = [[UIView alloc]initWithFrame:CGRectMake(0, yAxisDocAttachment, self.view.frame.size.width - cell.lblContent.frame.origin.x - 50, 80)];
viewAttachment.backgroundColor = [UIColor colorWithRed:234.0/255.0 green:234.0/255.0 blue:234.0/255.0 alpha:1.0];
viewAttachment.tag = indexPath.row;
viewAttachment.accessibilityIdentifier = msgDoc.Url;
viewAttachment.accessibilityLabel = msgDoc.Name;
[cell.viewAttachmentCollection addSubview:viewAttachment];
UIImageView *imgAttachment = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 52, 60)];
imgAttachment.image = [UIImage imageNamed:#"document.png"];
[viewAttachment addSubview:imgAttachment];
UILabel *lblFileName = [[UILabel alloc]initWithFrame:CGRectMake(65, 5, viewAttachment.frame.size.width - 65, 22)];
lblFileName.backgroundColor = [UIColor clearColor];
lblFileName.text = msgDoc.Name;
lblFileName.text = [lblFileName.text stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
lblFileName.textAlignment = NSTextAlignmentLeft;
lblFileName.font = [UIFont systemFontOfSize:10];
lblFileName.numberOfLines = 0;
[viewAttachment addSubview:lblFileName];
[lblFileName sizeToFit];
UILabel *lblFileType = [[UILabel alloc]initWithFrame:CGRectMake(65, 30, viewAttachment.frame.size.width - 65, 20)];
lblFileType.backgroundColor = [UIColor clearColor];
lblFileType.text = msgDoc.Name;
lblFileType.textAlignment = NSTextAlignmentLeft;
lblFileType.font = [UIFont systemFontOfSize:10];
[viewAttachment addSubview:lblFileName];
UILabel *lblDownload = [[UILabel alloc]initWithFrame:CGRectMake(65, 53, viewAttachment.frame.size.width - 65, 20)];
lblDownload.backgroundColor = [UIColor clearColor];
lblDownload.text = NSLocalizedString(#"click_to_download", nil);
lblDownload.textAlignment = NSTextAlignmentLeft;
lblDownload.font = [UIFont systemFontOfSize:10];
[viewAttachment addSubview:lblDownload];
UITapGestureRecognizer *gestureAttachment = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleAttachmentGesture:)];
[viewAttachment addGestureRecognizer:gestureAttachment];
yAxis = yAxis + 90;
yAxisDocAttachment = yAxisDocAttachment + 90;
cell.viewAttachmentHeightConstraint.constant = cell.viewAttachmentHeightConstraint.constant + 90;
}
}
cell.viewImageHeightConstraint.constant = 0;
if(indexPath.row != 0)
cell.viewImageLeftConstraint.constant = xAxis - 16;
else
cell.viewImageLeftConstraint.constant = xAxis;
for(MessageAttachment *msgDoc in thread.attachments)
{
if([msgDoc.Type isEqual:#"Image"])
{
isImage = YES;
cell.viewImageCollection.hidden = NO;
cell.viewImageTopConstraint.constant = 10;
cell.btnReplyTopConstraint.constant = 10;
[self createAttachmentImage:CGRectMake(xAxis, cell.viewImageHeightConstraint.constant + 10, self.view.frame.size.width - xAxis - 5, 480) cell:cell message:msgDoc indexPath:indexPath];
cell.viewImageHeightConstraint.constant = cell.viewImageHeightConstraint.constant + 5;
}
}
}
if(!isDoc)
{
cell.viewAttachmentCollection.hidden = YES;
cell.viewAttachmentHeightConstraint.constant = 0;
cell.viewAttachmentTopConstraint.constant = 0;
}
if(!isImage)
{
cell.viewImageCollection.hidden = YES;
cell.viewImageHeightConstraint.constant = 0;
cell.viewImageTopConstraint.constant = 0;
}
[cell.btnReplyCell setTitle:[NSString stringWithFormat:#"%# %#", NSLocalizedString(#"reply", nil),thread.sender.FirstName] forState:UIControlStateNormal];
[cell.btnReplyCell setTitle:[NSString stringWithFormat:#"%# %#", NSLocalizedString(#"reply", nil),thread.sender.FirstName] forState:UIControlStateDisabled];
[cell.btnReplyCell setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.btnReplyCell setTitleColor:[UIColor colorWithRed:199.0/255.0 green:192.0/255.0 blue:193.0/255.0 alpha:1.0] forState:UIControlStateDisabled];
if(thread.sender.SenderId != [[NSString stringWithFormat:#"%#", [[NSUserDefaults standardUserDefaults]objectForKey:#"UserId"]] intValue])
{
cell.btnReplyTopConstraint.constant = 10;
cell.btnReplyHeightConstraint.constant = 30;
cell.btnReplyBottomConstraint.constant = 12;
cell.btnReplyCell.titleLabel.textAlignment = NSTextAlignmentCenter;
cell.btnReplyCell.layer.cornerRadius = 7;
cell.btnReplyCell.tag = (int)indexPath.row;
cell.btnReplyCell.backgroundColor = [UIColor whiteColor];
cell.btnReplyCell.layer.borderColor = [[UIColor blackColor] CGColor];
cell.btnReplyCell.layer.borderWidth = 0.7;
cell.btnReplyCell.accessibilityIdentifier = [NSString stringWithFormat:#"%i", (int)arrBtnReply.count];
cell.btnReplyCell.titleLabel.font = [UIFont systemFontOfSize:12];
[cell.btnReplyCell addTarget:self action:#selector(replyTapped:) forControlEvents:UIControlEventTouchUpInside];
yAxis = yAxis + 20;
cell.btnReplyCell.accessibilityLabel = [NSString stringWithFormat:#"%f", yAxis];
cell.btnReplyCell.enabled = YES;
cell.btnReplyTopConstraint.constant = 10;
}
else
{
cell.btnReplyTopConstraint.constant = 10;
cell.btnReplyBottomConstraint.constant = 0;
cell.btnReplyCell.hidden = YES;
cell.btnReplyHeightConstraint.constant = 0;
cell.btnReplyCell.layer.cornerRadius = 7;
cell.btnReplyCell.backgroundColor = [UIColor colorWithRed:224.0/255.0 green:224.0/255.0 blue:224.0/255.0 alpha:1.0];
cell.btnReplyCell.enabled = NO;
}
[cell updateConstraintsIfNeeded];
[cell setNeedsLayout];
[cell layoutIfNeeded];
return cell;
}
}
#catch (NSException *exception) {
return cell;
}
}
I know that huge code, but what would be interrupting the smooth scroll ?

I describe a few assumptions:
You configure many constraints. It's bad for smooth scrolling. If your cell is complex and thus there are many contraints -> you can see twitching scroll.
Also I can see that you dynamically add / remove subview. Why do you do this? Why don't you configure label in the init method?
Sometimes shadow and cornerRadius can affect on smooth scrolling.
I think in your case main problem - it's constraints and dynamic add/deleting views.

Related

UI freezes in table view

My tableView freezes while reloading with rows more than 600. is there any solution for that.I am getting data in background thread and try to reload my table in main thread but still the issue is same.
this is my code in cellForRow..
if (![currentUID isEqualToString:[chatDict valueForKey:#"sender"]]) {
identifier = #"onlyRightChat";
}else{
identifier = #"onlyLeftChat";
}
UITableViewCell *cell ;
cell= [tableView dequeueReusableCellWithIdentifier:identifier ];
NSString *userName;
if ([chatDict valueForKey:#"sender_last_name"]) {
userName = [NSString stringWithFormat:#"%# %#",[chatDict valueForKey:#"sender_first_name"],[chatDict valueForKey:#"sender_last_name"]];
}else{
userName = [NSString stringWithFormat:#"%#",[chatDict valueForKey:#"sender_first_name"]];
}
NSString *str ;
if (![currentUID isEqualToString:[chatDict valueForKey:#"sender"]]) {
str = [NSString stringWithFormat:#"%#:\n%#",userName,[[Utils sharedObject] convertUnicodeToEmoji:[chatDict valueForKey:#"text"]]];
}else{
str = [NSString stringWithFormat:#"You:\n%#",[[Utils sharedObject] convertUnicodeToEmoji:[chatDict valueForKey:#"text"]]];
}
CGRect labelSize =[self getRectForString:str];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
TTTAttributedLabel *lbl = (TTTAttributedLabel *)[cell.contentView viewWithTag:5111];
UIView *lblBgView = (UIView *)[cell.contentView viewWithTag:5113];
UIView *bgView = (UIView *)[cell.contentView viewWithTag:5115];
UILabel *timeLbl = (UILabel *)[cell.contentView viewWithTag:5114];
UIImageView *userImgView = (UIImageView *)[cell.contentView viewWithTag:5116];
UILabel *onlineIcon = (UILabel *)[cell.contentView viewWithTag:onlineStatusTag];
onlineIcon.layer.cornerRadius = onlineIcon.frame.size.height/2.0;
onlineIcon.clipsToBounds = YES;
lbl.backgroundColor = [UIColor clearColor];
lbl.enabledTextCheckingTypes = NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber|NSTextCheckingTypeAddress;
lbl.delegate = self;
if (![currentUID isEqualToString:[chatDict valueForKey:#"sender"]]) {
lbl.linkAttributes = #{NSForegroundColorAttributeName:[UIColor colorWithRed:91/255.0f green:135/255.0f blue:198/255.0f alpha:1.0] ,NSUnderlineStyleAttributeName: #(NSUnderlineStyleSingle)};//[UIColor colorWithRed:119/255.0f green:195/255.0f blue:66/255.0f alpha:1.0]
}else{
lbl.linkAttributes = #{NSForegroundColorAttributeName:[UIColor colorWithRed:194/255.0f green:228/255.0f blue:255/255.0f alpha:1.0] ,NSUnderlineStyleAttributeName: #(NSUnderlineStyleSingle)};//[UIColor colorWithRed:119/255.0f green:195/255.0f blue:66/255.0f alpha:1.0]
}
if ([currentUID isEqualToString:[chatDict valueForKey:#"sender"]]) {
onlineIcon.hidden = YES;
}else{
onlineIcon.hidden = NO;
NSString *status = [chatDict valueForKey:#"status"];
if(status){
if([status isEqualToString:#"online"]){
onlineIcon.backgroundColor = [UIColor colorWithRed:81/255.0 green:217/255.0 blue:93/255.0 alpha:1.0];
}else if([status isEqualToString:#"offline"]){
onlineIcon.backgroundColor = [UIColor yellowColor];
}else{
onlineIcon.backgroundColor = [UIColor colorWithRed:214/255.0 green:103/255.0 blue:101/255.0 alpha:1.0];
}
}else{
onlineIcon.backgroundColor = [UIColor yellowColor];
}
}
userImgView.layer.cornerRadius = userImgView.frame.size.height/2;
userImgView.clipsToBounds = YES;
[userImgView sd_setImageWithURL:[NSURL URLWithString:[chatDict valueForKey:#"sender_picture"]]placeholderImage:[UIImage imageNamed:#"default_avatar"]];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(userImageViewTap:)];
tapGesture.numberOfTapsRequired = 1;
userImgView.userInteractionEnabled = YES;
[userImgView addGestureRecognizer:tapGesture];
// NSLog(#"cell.frame.size.width %f",cell.frame.size.width);
float width = cell.frame.size.width;
float height = cell.frame.size.height;
if (![currentUID isEqualToString:[chatDict valueForKey:#"sender"]])
{
bgView.frame = CGRectMake(width- labelSize.size.width-31-20-35,0,labelSize.size.width+31+20,cell.frame.size.height);
lblBgView.frame = CGRectMake(0,10,bgView.frame.size.width-15,labelSize.size.height+10);
lbl.frame = CGRectMake(8, 0, lblBgView.frame.size.width-16, labelSize.size.height+10);
timeLbl.frame = CGRectMake(width-170,height-25, 120,fontSize);
timeLbl.textAlignment = NSTextAlignmentRight;
}else{
bgView.frame = CGRectMake(35,0,labelSize.size.width+31+20,cell.frame.size.height);
lblBgView.frame = CGRectMake(15,10,bgView.frame.size.width-15,labelSize.size.height+10);
lbl.frame = CGRectMake(8, 0, lblBgView.frame.size.width-16, labelSize.size.height+10);
timeLbl.frame = CGRectMake(55,height-25, 120,fontSize);
timeLbl.textAlignment = NSTextAlignmentLeft;
}
NSDate* dateComment = [[Utils sharedObject] StringToDate:[chatDict valueForKey:#"created_at"] withFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
timeLbl.text = [[Utils sharedObject] relativeTimestamp:dateComment];
timeLbl.font = [UIFont fontWithName:#"Lato-Regular" size:fontSize-3.0];
lblBgView.layer.cornerRadius = 8.0f;
lblBgView.clipsToBounds = YES;
lbl.layer.cornerRadius = 8.0f;
lbl.font = [UIFont fontWithName:#"Lato-Regular" size:fontSize];
lbl.numberOfLines = 0;
lbl.clipsToBounds = YES;
if (str!=(id)[NSNull null])
{
if (![currentUID isEqualToString:[chatDict valueForKey:#"sender"]]) {
lbl.text = str;
}else{
NSDictionary *attrDict = #{ NSFontAttributeName : [UIFont fontWithName:#"Lato-Regular" size:fontSize], NSForegroundColorAttributeName : [UIColor colorWithRed:146/255.0 green:183/255.0 blue:201/255.0 alpha:1.0]};
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:#"You:\n" attributes: attrDict];
NSDictionary *attrDict1 = #{ NSFontAttributeName : [UIFont fontWithName:#"Lato-Regular" size:fontSize]};
NSMutableAttributedString *attrString1 = [[NSMutableAttributedString alloc] initWithString:[[Utils sharedObject] convertUnicodeToEmoji:[chatDict valueForKey:#"text"]] attributes: attrDict1];
[attrString appendAttributedString:attrString1];
lbl.text = str;
lbl.textColor = [UIColor whiteColor];
}
}else{
lbl.text= #"";
}
return cell;
}
and reload call from method..
-(void)getChatTextFromLocalDB{
// [self showLoadingView];
NSString *databaseKey = [NSString stringWithFormat:#"%#-%#",[self.m_dictInfo valueForKey:#"rid"],[[NSUserDefaults standardUserDefaults] objectForKey:#"rid"]];
NSString *localDBPath=[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/GroupChat.plist"];
NSMutableDictionary *root = [[[NSMutableDictionary alloc] initWithContentsOfFile:localDBPath] mutableCopy];
NSMutableArray *chatDictAry = [root objectForKey:databaseKey];
NSString *localDBPath1=[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/GeoConnectChat.plist"];
NSMutableDictionary *root1 = [[[NSMutableDictionary alloc] initWithContentsOfFile:localDBPath1] mutableCopy];
NSMutableArray *temp = [root1 objectForKey:#"chatDeleted"];
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"created_at" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
NSArray *sortedArray = [chatDictAry sortedArrayUsingDescriptors:sorters];
NSString *lastMsgRid;
[chatDictAry removeAllObjects];
[chatDictAry addObjectsFromArray:sortedArray];
if(chatDictAry.count||[temp containsObject:databaseKey ]){
[self.chatArray removeAllObjects];
for (NSDictionary *dict in chatDictAry) {
if(!([g_Delegate.grpBlockByMeList containsObject:[dict valueForKey:#"sender"]]||[g_Delegate.grpBlockMeList containsObject:[dict valueForKey:#"sender"]])){
[self.chatArray addObject:dict];
if([dict valueForKey:#"rid"])
lastMsgRid = [dict valueForKey:#"rid"] ;
[self.usersArray addObject:[dict valueForKey:#"sender"]];
}
}
[root writeToFile:localDBPath atomically:YES];
dispatch_async(dispatch_get_main_queue(), ^(void){
[self hideLoadingView];
});
if (self.chatArray.count) {
if(tablePositionTop){
CGSize beforeContentSize = self.chatTableView.contentSize;
[self.chatTableView reloadData];
CGSize afterContentSize = self.chatTableView.contentSize;
CGPoint afterContentOffset = self.chatTableView.contentOffset;
CGPoint newContentOffset = CGPointMake(afterContentOffset.x, afterContentOffset.y + afterContentSize.height - beforeContentSize.height);
self.chatTableView.contentOffset = newContentOffset;
}
else{
[self.chatTableView reloadData];
int64_t delayInSeconds = 0.2f;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
if(actualSelf){
[self.chatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.chatArray count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
});
}
[self getUsersOnlineStatus];
if (isFirstTime) {
isFirstTime = NO;
[self getRemainingListFromServerWithLastMsgId:lastMsgRid];
}else{
// [self hideLoadingView];
}
}else{
[self hideLoadingView];
}
}
else
{
if (isFirstTime) {
isFirstTime = NO;
[self showLoadingView];
[self getAllMessages];
}
}
}
I suggest you watch Session 211 of WWDC 2012, Building Concurrent User Interfaces and apply the concepts there. This features cells whose contents are independently queried and rendered.
The basic concept is as follows:
1. In tableView:cellForRowAtIndexPath, a cell is instantiated.
2. In the same method, an operation for retrieving the data to populate the cell is created and stored into a dictionary. A reference to the cell is passed to the operation. The operation has a completion handler that populates the cell and removes the operation from the dictionary.
3. Before the cell is returned from the method, the operation is added to an operation queue.
4. In tableView:didEndDisplayingCell:forRowAtIndexPath, operations for cells that have moved off-screen are cancelled and removed from the dictionary.

How to Create multiple Tags inside UITableViewCell and set action to each tags

I'm creating Tags inside _ParentContentView subView in UITableView Cell. following code create all tags manually and might increase memory for each tags and it's subViews
i like to have Action for each tag
i like to have all tags inside tableivewCell with out scrolling insdie
table view cell. mean tableviewCell should increase/decrease the
content size automatically.
SpecialityCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int xPosition = 0;
int yPosition = 0;
for (NSInteger buttonCount = 0; buttonCount<=dummyString.count-1; buttonCount++)
{
UIView *parentView = [[UIView alloc]init];
parentView.frame = CGRectMake(10, 0, 150, 40);
[parentView setFrame:CGRectMake(xPosition+10, yPosition,100, 25)];
xPosition = xPosition+130;
parentView.backgroundColor = [UIColor blackColor];
parentView.alpha = 0.5;
parentView.layer.cornerRadius = 15;
UIImageView *childView =[[UIImageView alloc]init];
childView.frame = CGRectMake(5, (parentView.frame.size.height-20)/2, 20, 20);
childView.alpha = 1.0;
childView.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png",[appDelegate.topinImageArray objectAtIndex:3]]];
childView.layer.cornerRadius = 10;
[parentView addSubview:childView];
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.frame = CGRectMake(childView.frame.size.width+10, (parentView.frame.size.height-30)/2, 80, 30);
nameLabel.text = [NSString stringWithFormat:#"%#", [dummyString objectAtIndex:buttonCount]];
nameLabel.textColor = [UIColor whiteColor];
[parentView addSubview:nameLabel];
[cell._ParantContentView addSubview:parentView];
if((buttonCount+1)%3==0)//4 means how many buttons you need for a row
{
yPosition+= 50;
xPosition= 10;
}
}
like this you can do.
label1 = (UILabel*)[cell.contentView viewWithTag:401];
CGFloat widthLabelHeader = CGRectGetWidth(orderTable.frame)/7;
if(!label1)
{
label1 = [[UILabel alloc]init];
label1.frame = CGRectMake(0, 0, widthLabelHeader, 60);
label1.layer.borderWidth = 0.5;
label1.tag = 401;
label1.font = [UIFont fontWithName:#"LaoSangamMN" size:14];
[cell.contentView addSubview:label1];
}
label1.textAlignment = NSTextAlignmentCenter;
label2 = (UILabel*)[cell.contentView viewWithTag:402];
if(!label2)
{
label2 = [[UILabel alloc]init];
label2.frame = CGRectMake(CGRectGetMaxX(label1.frame), 0, widthLabelHeader, 60);
label2.layer.borderWidth = 0.5;
label2.tag = 402;
label2.font = [UIFont fontWithName:#"LaoSangamMN" size:14];
[cell.contentView addSubview:label2];
}
label2.textAlignment = NSTextAlignmentCenter;
label3 = (UILabel*)[cell.contentView viewWithTag:403];
if(!label3)
{
label3 = [[UILabel alloc]init];
label3.frame = CGRectMake(CGRectGetMaxX(label2.frame), 0, widthLabelHeader, 60);
label3.layer.borderWidth = 0.5;
label3.tag = 403;
label3.font = [UIFont fontWithName:#"LaoSangamMN" size:14];
[cell.contentView addSubview:label3];
}
label3.textAlignment = NSTextAlignmentCenter;
label4 = (UILabel*)[cell.contentView viewWithTag:404];
if(!label4)
{
label4 = [[UILabel alloc]init];
label4.frame = CGRectMake(CGRectGetMaxX(label3.frame), 0, widthLabelHeader, 60);
label4.layer.borderWidth = 0.5;
label4.tag = 404;
label4.font = [UIFont fontWithName:#"LaoSangamMN" size:14];
label4.numberOfLines = 4;
[cell.contentView addSubview:label4];
}
label4.textAlignment = NSTextAlignmentCenter;
label5 = (UILabel*)[cell.contentView viewWithTag:405];
if(!label5)
{
label5 = [[UILabel alloc]init];
label5.frame = CGRectMake(CGRectGetMaxX(label4.frame), 0, widthLabelHeader, 60);
label5.layer.borderWidth = 0.5;
label5.tag = 405;
label5.font = [UIFont fontWithName:#"LaoSangamMN" size:14];
[cell.contentView addSubview:label5];
}
label5.textAlignment = NSTextAlignmentCenter;
label6 = (UILabel*)[cell.contentView viewWithTag:406];
if(!label6)
{
label6 = [[UILabel alloc]init];
label6.frame = CGRectMake(CGRectGetMaxX(label5.frame), 0, widthLabelHeader, 60);
label6.layer.borderWidth = 0.5;
label6.tag = 406;
label6.font = [UIFont fontWithName:#"LaoSangamMN" size:14];
[cell.contentView addSubview:label6];
}
label6.textAlignment = NSTextAlignmentCenter;
UIButton *editBtn = (UIButton*)[cell.contentView viewWithTag:407];
if(!editBtn)
{
editBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
editBtn.frame = CGRectMake(CGRectGetMaxX(label6.frame), 0, widthLabelHeader, 60);
editBtn.layer.borderWidth = 2.5;
[editBtn addTarget:self action:#selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
[editBtn setTintColor:[UIColor blackColor]];
editBtn.tag = 407;
[cell.contentView addSubview:editBtn];
UIImageView *editimg = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(editBtn.frame),0, CGRectGetWidth(label6.frame), 60)];
[editimg setImage:[UIImage imageNamed:#"edit-01.png"]];
[cell.contentView addSubview:editimg];
}
dict1 = [arrayFiltered objectAtIndex:indexPath.row];
if( dict1)
{
NSString *strName = [dict1 objectForKey:#"i_name"];
label1.text = #"";
label1.text = strName;
label1.backgroundColor = [UIColor whiteColor];
label1.numberOfLines = 2;
label2.text = #"";
label2.text = [dict1 objectForKey:#"i_code" ];
label2.backgroundColor = [UIColor whiteColor];
label2.numberOfLines = 2;
NSString *strCategory = [dict1 objectForKey:#"i_category"];
NSArray *arrValuesTempCat = [strCategory componentsSeparatedByString:#","];
NSMutableArray *arrKeyTempCat = [NSMutableArray new];
for (int i = 0; i < arrValuesTempCat.count; i++)
{
NSString *strValue = [arrValuesTempCat objectAtIndex:i];
if ([[categoryDict allKeys] containsObject:strValue]) {
NSString *str = [categoryDict objectForKey:strValue];
if (str.length > 0)
{
[arrKeyTempCat addObject:str];
}
}
}
if ([arrKeyTempCat containsObject:#""])
{
[arrKeyTempCat removeObject:#""];
}
if ([arrKeyTempCat containsObject:#" "])
{
[arrKeyTempCat removeObject:#" "];
}
NSString *strCategoryKeysParam = nil;
if (arrKeyTempCat.count == 1)
{
strCategoryKeysParam = [arrKeyTempCat objectAtIndex:0];
}
else
{
strCategoryKeysParam = [arrKeyTempCat componentsJoinedByString:#","];
}
label3.text= #"";
label3.text = strCategoryKeysParam;
label3.backgroundColor = [UIColor whiteColor];
label3.numberOfLines = 2;
NSString *strElements = [dict1 objectForKey:#"i_elements"];
NSArray *arrKeysTemp = [strElements componentsSeparatedByString:#","];
NSMutableArray *arrValuesTemp = [NSMutableArray new];
for (int i = 0; i < arrKeysTemp.count; i++)
{
NSString *strKey = [arrKeysTemp objectAtIndex:i];
if ([[elementsDict allKeys] containsObject:strKey]) {
NSString *strValue = [elementsDict objectForKey:strKey];
[arrValuesTemp addObject:strValue];
}
}
NSString *strValues = [arrValuesTemp componentsJoinedByString:#","];
label4.text = #"";
label4.text = strValues;
label4.backgroundColor = [UIColor whiteColor];
label5.text = #"";
label5.text = [dict1 objectForKey:#"i_quantity_produced" ];
label5.backgroundColor = [UIColor whiteColor];
label6.text = #"";
label6.text = [dict1 objectForKey:#"active_status" ];
label6.backgroundColor = [UIColor whiteColor];
[editBtn setTitle:#"" forState:UIControlStateNormal];
NSString *idStr = [NSString stringWithFormat:#"%d",[[dict1 objectForKey:#"i_id"] intValue]];
NSLog(#"ids : %#, dict : %#",idStr, dict1);
[editBtn addTarget:self action:#selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
editBtn.accessibilityIdentifier = idStr;
NSString *strID = editBtn.accessibilityIdentifier;
NSLog(#"str ID : %#",strID);
editItemId = [[dict1 objectForKey:#"i_id"]intValue];
NSLog(#"Edited Item : %d",editItemId);
// [appDelegate hideIndicator];
}
}
For set row height according to it's content you should set tableview's two properties
_tableViewOne.estimatedRowHeight = 50; //minimum row height
_tableViewOne.rowHeight = UITableViewAutomaticDimension;
so it will take row height according to it's content.
Don't use :
heightForRowAtIndexPath method when using above code.

UIButton not select the correct cell

in my tableview I have a button in the custom cell
I used the delegates to take an action to the button
The button image changes only on the selected cell
My problem is this:
When I press the button happens:
the selected cell is working properly and the button changes correctly (correct)
the second immediately after the selected cell does not change the button (corrected)
the third cell repeats the action of the selected cell (wrong)
This is repeated endlessly do not understand why
 The button should change only the selected cell and not on other non-selected
Can you help me please?
-(void)ButtonPressedGoPoint:(FFCustomCellWithImage *)custom button:(UIButton *)gopointpressed {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"it_IT"]];
NSNumber *likeCount = [numberFormatter numberFromString:custom.CountGoPoint.text];
if (!custom.AddGoPoint.selected) {
NSLog(#"TastoSelezionato");
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
custom.CountGoPoint.text = [NSString stringWithFormat:#"%#", likeCount];
[custom.AddGoPoint setBackgroundImage:[UIImage imageNamed:#"FFIMG_Medal_Blu"] forState:UIControlStateNormal];
}
else {
if ([likeCount intValue] > 0) {
likeCount = [NSNumber numberWithInt:[likeCount intValue] - 1];
custom.CountGoPoint.text = [NSString stringWithFormat:#"%#", likeCount];
}
NSLog(#"TastoDeselezionato");
[custom.AddGoPoint setBackgroundImage:[UIImage imageNamed:#"FFIMG_MedalADD"] forState:UIControlStateNormal];
}
custom.AddGoPoint.selected = !custom.AddGoPoint.selected;
}
This is my implementation of the tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
self.PostDetails = [ArrayforPost objectAtIndex:indexPath.row];
static NSString *IdentificazioneCellaIMG = #"CellaIMG";
FFCustomCellWithImage * CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
if (CellaIMG == nil) {
CellaIMG = [[FFCustomCellWithImage alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IdentificazioneCellaIMG ];
}
CellaIMG.delegate = self;
CellaIMG.tag = indexPath.row;
[CellaIMG.AddGoPoint setTag:indexPath.row];
if ([self AssignedGoPointToPost:self.PostDetails]) {
CellaIMG.AddGoPoint.selected =YES;
[CellaIMG.AddGoPoint setImage:[UIImage imageNamed:#"FFIMG_Medal_Blu"] forState:UIControlStateNormal];
} else {
CellaIMG.AddGoPoint.selected =NO;
[CellaIMG.AddGoPoint setImage:[UIImage imageNamed:#"FFIMG_MedalADD"] forState:UIControlStateNormal];
}
NSString *FotoPostSocial = [self.PostDetails objectForKey:FF_POST_IMMAGINE];
CellaIMG.FotoPost.file = (PFFile *)FotoPostSocial;
[CellaIMG.FotoPost loadInBackground];
CellaIMG.FotoPost.layer.masksToBounds = YES;
CellaIMG.FotoPost.layer.cornerRadius = 2.0f;
CellaIMG.FotoPost.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.backgroundCell.layer.masksToBounds = YES;
CellaIMG.backgroundCell.layer.cornerRadius = 2.0f;
CellaIMG.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.backgroundCell.layer.borderWidth = 1.0f;
CellaIMG.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
CellaIMG.LeggiCommentoButton.layer.cornerRadius = 2.0f;
CellaIMG.FotoProfilo.layer.masksToBounds = YES;
CellaIMG.FotoProfilo.layer.cornerRadius = 25.0f;
CellaIMG.FotoProfilo.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.TestoPost.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [self.PostDetails objectForKey:FF_POST_TEXT];
CellaIMG.TestoPost.text = text;
[CellaIMG.TestoPost setLineBreakMode:NSLineBreakByTruncatingTail];
NSString *NomeUser = [[self.PostDetails objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
CellaIMG.NomeUtente.text = NomeUser;
NSString *ImmagineUtente = [[self.PostDetails objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
CellaIMG.FotoProfilo.file = (PFFile *)ImmagineUtente;
[CellaIMG.FotoProfilo loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, AltezzaLabel); }
else {
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, 65);
}
return CellaIMG;
}
}

Why UITableview data are overlapping?

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

What will be the numberOfRowsInSection return type for uitableview when XML data is retrieved?

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
}

Resources