Data inside tableview are mixed-up after scrolling - ios

I've read many questions and tried the solutions but I still couldn't resolve the problem with my tableview.
After scrolling, the data in the rows of the tableview got interchanged and sometimes missing.
Here's my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *modifierCheckCell = #"BGMModifierCheckCell";
BGMModifierCheckCell *cell = nil;
cell = (BGMModifierCheckCell *)[tableView dequeueReusableCellWithIdentifier:modifierCheckCell];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:modifierCheckCell owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (BGMModifierCheckCell *)currentObject;
break;
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSArray *optionIds = [[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:#"optnItem"] objectAtIndex:indexPath.row];
BGMOptnCats *optnCat = [BGMOptnCats MR_findFirstByAttribute:#"iOptnCatId" withValue:[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:#"optnCatId"]];
[optionIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
__block int optnTag = [obj intValue];
BGMItemDayOptns *item = [BGMItemDayOptns MR_findFirstByAttribute:#"iItemDayOptnId" withValue:obj];
[item.optns.optnLangs enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
BGMOptnLangs *lang = (BGMOptnLangs *)obj;
if ([lang.sLangCode isEqualToString:#"en"]) {
NSString *optn = [NSString stringWithFormat:#"%#", lang.sOptnName];
if ([optnCat.sOptnType isEqualToString:#"single"]) {
RadioButton *rb1 = [[RadioButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
[rb1 setGroupID:indexPath.section AndID:optnTag AndTitle:optn];
rb1.delegate = self;
if (idx == 0) {
[cell.firstOption addSubview:rb1];
} else if (idx == 1) {
[cell.secondOption addSubview:rb1];
} else if (idx == 2) {
[cell.thirdOption addSubview:rb1];
}
} else if ([optnCat.sOptnType isEqualToString:#"multiple"]) {
SSCheckBoxView *checkBox = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(0, 0, 200, 40) style:kSSCheckBoxViewStyleMono checked:NO];
checkBox.tag = optnTag;
[checkBox setStateChangedTarget:self selector:#selector(checkBoxViewChangedState:)];
[checkBox setText:#""];
[checkBox setText:optn];
if (idx == 0) {
[cell.firstOption addSubview:checkBox];
} else if (idx == 1) {
[cell.secondOption addSubview:checkBox];
} else if (idx == 2) {
[cell.thirdOption addSubview:checkBox];
}
}
}
}];
}];
}
return cell;
}

The problem is that your cells are being reused. So the rows are interchanged when scrolling.
Set the cell content outside of the if (cell == nil).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *modifierCheckCell = #"BGMModifierCheckCell";
BGMModifierCheckCell *cell = nil;
cell = (BGMModifierCheckCell *)[tableView dequeueReusableCellWithIdentifier:modifierCheckCell];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:modifierCheckCell owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (BGMModifierCheckCell *)currentObject;
break;
}
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSArray *optionIds = [[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:#"optnItem"] objectAtIndex:indexPath.row];
BGMOptnCats *optnCat = [BGMOptnCats MR_findFirstByAttribute:#"iOptnCatId" withValue:[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:#"optnCatId"]];
[optionIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
__block int optnTag = [obj intValue];
BGMItemDayOptns *item = [BGMItemDayOptns MR_findFirstByAttribute:#"iItemDayOptnId" withValue:obj];
[item.optns.optnLangs enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
BGMOptnLangs *lang = (BGMOptnLangs *)obj;
if ([lang.sLangCode isEqualToString:#"en"]) {
NSString *optn = [NSString stringWithFormat:#"%#", lang.sOptnName];
if ([optnCat.sOptnType isEqualToString:#"single"]) {
RadioButton *rb1 = [[RadioButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
[rb1 setGroupID:indexPath.section AndID:optnTag AndTitle:optn];
rb1.delegate = self;
if (idx == 0) {
[cell.firstOption addSubview:rb1];
} else if (idx == 1) {
[cell.secondOption addSubview:rb1];
} else if (idx == 2) {
[cell.thirdOption addSubview:rb1];
}
} else if ([optnCat.sOptnType isEqualToString:#"multiple"]) {
SSCheckBoxView *checkBox = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(0, 0, 200, 40) style:kSSCheckBoxViewStyleMono checked:NO];
checkBox.tag = optnTag;
[checkBox setStateChangedTarget:self selector:#selector(checkBoxViewChangedState:)];
[checkBox setText:#""];
[checkBox setText:optn];
if (idx == 0) {
[cell.firstOption addSubview:checkBox];
} else if (idx == 1) {
[cell.secondOption addSubview:checkBox];
} else if (idx == 2) {
[cell.thirdOption addSubview:checkBox];
}
}
}
}];
}];
return cell;
}

you need to remove your subviews because each time CellForRowAtIndexpath is called it will create a subview so before adding new subview remove the previous one
for (UIView *view in cell.contentView.subviews) {
[view removeFromSuperview];
}

Related

How to use multiple CustomCells with UISegmentedControl Objective C

I have a small issue with the multiple CustomCells by using SegmentedControl. I have imported a framework HMSegmentedControl with 4 segmentedcontrols like (Admin, Engineer, Doctor, Employee). Now the problem is how to use multiple custom cells like (AdminCellList, EngineerCellList, DoctorCellList, EmployeeListCell). When Admin SegmentedControl is Clicked AdminCellList should be loaded and so on. Following is what i have tried. TIA.
MYViewController.h
#interface MYViewController : UIViewController
{
NSUInteger currentScreen;
}
MYViewController.m
self.AdminView.hidden = NO;
self.EngineerView.hidden = YES;
self.DoctorView.hidden = YES;
self.EmployeeView.hidden = YES;
currentScreen=0;
[self.scrollView addSubview:self.AdminView];
self.edgesForExtendedLayout = UIRectEdgeNone;
CGFloat viewWidth = CGRectGetWidth(self.view.frame);
HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:#[#"Admin", #"Engineer", #"Doctor", #"Employee"]];
segmentedControl.frame = CGRectMake(0, 0, viewWidth, 45);
segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
segmentedControl.backgroundColor = [UIColor colorWithRed:170/255.0 green:170/255.0 blue:170/255.0 alpha:1.0];
segmentedControl.selectionIndicatorColor = [UIColor blackColor];
segmentedControl.selectionIndicatorHeight = 2.0f;
segmentedControl.verticalDividerEnabled = YES;
segmentedControl.verticalDividerColor = [UIColor blackColor];
segmentedControl.verticalDividerWidth = 1.0f;
segmentedControl.borderColor = [UIColor blackColor];
[segmentedControl setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
return attString;
}];
[segmentedControl addTarget:self action:#selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segmentedControl];
}
- (void)segmentedControlChangedValue:(UISegmentedControl *)segment
{
if(segment.selectedSegmentIndex == 0) {
currentScreen=0;
//Loading Service
}
else if(segment.selectedSegmentIndex == 1) {
currentScreen=1;
//Loading Service
}
else if(segment.selectedSegmentIndex == 2) {
currentScreen=2;
//Loading Service
}
else if(segment.selectedSegmentIndex == 3) {
currentScreen=3;
//Loading Service
}
}
- (void)uisegmentedControlChangedValue:(UISegmentedControl *)segmentedControl {
NSLog(#"Selected index %ld", (long)segmentedControl.selectedSegmentIndex);
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
AdminCellList *cell = (AdminCellList *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"AdminCellList" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (AdminCellList *) currentObject;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
Everything looks good, just need some additions:
1.Reload table each time user changes segment.
2.Put check inside cellForRowAtIndexPath according to currentScreen and load corresponding cell with custom class.
- (void)segmentedControlChangedValue:(UISegmentedControl *)segment {
if(segment.selectedSegmentIndex == 0) {
currentScreen=0;
}
else if(segment.selectedSegmentIndex == 1) {
currentScreen=1;
}
....... more code
[myTableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
if (currentScreen == 0) {
AdminCellList *cell = (AdminCellList *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"AdminCellList" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (AdminCellList *) currentObject;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
}
}
} else if (currentScreen == 1) {
//Same code for cell as AdminCellList
EngineerCellList *cell = (EngineerCellList *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"EngineerCellList" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (EngineerCellList *) currentObject;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
}
}
} else if (currentScreen == 2) {
//Similar custom cell code here as above
} else {
//Similar custom cell code here as above
}
}

button tag issue with UISearchBar

I need to set a tag for the button created on the table view cell.
I implemented the UISearchBar and it works well.
Issue is after filtering the tableView cell, its indexpath.row changes as I am setting
'button.tag = indexPath.row'.
Is there a way to keep the row number constant for every cell?
Or is there any other solution?
Note: I have multiple sections in one UITableView and isFiltered is BOOL value which indicates user have started to type text in UISearchBar.
Implemented Searching with help of https://github.com/kwylez/IndexedTable
In cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"CheckBoxedCell";
// NSString *cellId = [NSString stringWithFormat:#"Section:%d Row:%d",indexPath.section,indexPath.row];
CheckBoxedCellClass *cell = (CheckBoxedCellClass *)[self.tableViewContact dequeueReusableCellWithIdentifier:cellId];
if(!cell)
{
NSArray *nib;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass" owner:self options:nil];
}
else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass_iPad" owner:self options:nil];
}
for (id object in nib)
{
if([object isKindOfClass:[CheckBoxedCellClass class]])
{
cell = (CheckBoxedCellClass *)object;
break;
}
}
cell = [nib objectAtIndex:0];
}
SaveCheckBoxedView *saveContact;
if(isFiltered == YES)
{
saveContact = [filterdArray objectAtIndex:indexPath.row];
cell.nameLabel.text = saveContact.nameString;
}
else
{
saveContact = [mutableArray objectAtIndex:indexPath.row];
cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
}
//cell.nameLabel.text = saveContact.nameString;
cell.companyLabel.text = saveContact.companyString;
cell.invIdLabel.text = [NSString stringWithFormat:#"%d", saveContact.invitId];
//set fonts
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:10.0]];
}
else
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:14.0]];
}
//handling check box
NSInteger rowNumber = 0;
for(NSInteger i = 0; i < indexPath.section ; i++)
{
rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
/*if([indexPath compare:self.lastIndexPath] == NSOrderedSame)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSString *finalIntId = [mutableArrayOfIds objectAtIndex:rowNumber];
NSLog(#"Tagged checked button id = %#", finalIntId);
[arrayOfIds addObject:finalIntId];
}*/
UIButton *checkBox;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
}
else
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
}
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:event:) forControlEvents:UIControlEventTouchUpInside];
if(isFiltered == YES)
{
checkBox.tag = ;
}
else
{
checkBox.tag = rowNumber;
}
[cell.contentView addSubview:checkBox];
return cell;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
if(isFiltered == YES) {
return Nil;
} else {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
if (title == UITableViewIndexSearch) {
CGRect searchBarFrame = self.searchDisplayController.searchBar.frame;
[tableView scrollRectToVisible:searchBarFrame animated:YES];
return -1;
} else {
NSInteger count = 0;
for (NSString *character in arrayOfCharacters) {
if ([character isEqualToString:title]) {
return count;
}
count ++;
}
return 0;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(isFiltered == YES) {
return 1;
} else {
return [arrayOfCharacters count];
//return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(isFiltered == YES) {
return [filterdArray count];
} else {
//return [mutableArray count];
return [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:section]] count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if ([arrayOfCharacters count] == 0) {
return #"";
}
return [NSString stringWithFormat:#"%#", [arrayOfCharacters objectAtIndex:section]];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0)
{
isFiltered = NO;
}
else
{
isFiltered = YES;
filterdArray = [[NSMutableArray alloc] init];
for (SaveCheckBoxedView *contact in mutableArray)
{
NSRange nameRange = [contact.nameString rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound)
{
[filterdArray addObject:contact];
}
}
}
[self.tableViewContact reloadData];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filterdArray removeAllObjects];
if(searchString.length > 0)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.mySearchBar.text];
for (NSString *key in arrayOfCharacters)
{
NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate];
[filterdArray addObjectsFromArray:matches];
}
}
return YES;
}
I am describing one way to do so, you may find better way.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filterdArray removeAllObjects];
if(searchString.length > 0)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.mySearchBar.text];
for (NSString *key in arrayOfCharacters)
{
NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate];
/****see bellow****/
[filterdArray addObjectsFromArray:matches];
}
}
return YES;
}
Try to find the row number of each object of "matches". that will be the tag of your buttons. Make filterdArray an array of dictionary. Add 2 field to dictionary. one for tag another for value. in cellForRowAtIndexPath.
if(isFiltered == YES)
{
checkBox.tag = [filterdArray objectForKey: #"tag"] ;
}
else
{
checkBox.tag = rowNumber;
}

uitableviewcells are overlapping first 2 cells of 3 overlap

I have been trying to figure out if my cells are overlapping but I failed. My table contains 3 entries - the first 2 get overlapped but the 3rd one doesn't. I have searched on the net and found that variables should be defined locally. I have taken that advice but sadly, it didn't help.
Below is the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *rung;
if (indexPath.row%2 == 0) {
// 0.662745 0.662745 0.662745
rung=[UIColor colorWithRed:0.802745 green:0.802745 blue:0.802745 alpha:1];
color=NO;
}
else {
// 0.972549 0.972549 1
//0.411765 0.411765 0.411765
rung=[UIColor colorWithRed:0.862745 green:0.862745 blue:0.862745 alpha:1];
color=YES;
}
//static NSString *MyIdentifier = #"Identifier";
NSLog(#"====IndexPath is %d",indexPath.row);
ChatSlideDC *slide = [[HMMainManager getSharedInstance].currentMeeting.resumedChatMessages objectAtIndex:indexPath.section];
ChatMessageDC *message;
message = [[slide ChatMessageArray]objectAtIndex:indexPath.row];
NSLog(#"%i",indexPath.row);
NSLog(#"%#",message.senderEmail);
NSLog(#"====Message Type is %#",message.MessageType);
//--storing Email-ID for Pics
UIImage *avatar;
if(message.AttendeeID)
{
avatar= [(AppDelegate *)[[UIApplication sharedApplication]delegate] getAvatar:message.AttendeeID andAttendeEmail:message.senderEmail];
}
//
NSLog(#"%#",message.Message);
if ([message.MessageType isEqualToString: #"0"] || [message.MessageType isEqualToString:#"1"]) {
ChatCustomCell * cell = (ChatCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"ChatCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ChatCustomCell" owner:self options:nil];
cell = (ChatCustomCell*)[nib objectAtIndex:0];
}
// cell.backgroundImage.backgroundColor=rung;
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//cell.backgroundColor=rung;
cell.lblSaid.text =#"Said";
cell.lblName.text =message.SenderName;
cell.lblText.text =message.Message;
NSLog(#"manager strID: %# chat cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
NSLog(#"%# == %#",message.AttendeeID,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID);
[cell.imgThumbUserPic setImage:[UIImage imageNamed:#"updateProfileIco.png"]];
// if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
// cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
cell.imgThumbUserPic.image = avatar;
// }
cell.selectionStyle = UITableViewCellEditingStyleNone;
// [message release];
return cell;
}
if ([message.MessageType isEqualToString:#"2"] || [message.MessageType isEqualToString:#"3"] ) {
if ([message.MessageType isEqualToString:#"3"] || (message.question && [message.question length]>0)) {
//show asnwer cell
// AnswerCustomCell * cell = (AnswerCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"AnswerCustomCell"];
NSMutableArray *answerquestArray= [[[HMMainManager getSharedInstance] currentMeeting]questionAnswerArray];
// UITableViewCell *newCell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"abc"];
int width=300,height=164,totalHeight;;
// AnswerMultipleCell * cell;
int questionIndex;
QuestionWithAnswers *qwa;
for (int i=0;i<answerquestArray.count;i++) {
qwa=[answerquestArray objectAtIndex:i];
NSLog(#"");
if ([qwa.questionID isEqualToString:message.QuestionID]) {
break;
}
}//end for
// newCell.frame=CGRectMake(0, totalHeight, width, height);
ChatMessageDC *answersInArr;
int i=0;
for (i=0;i<[qwa.answersMArray count];i++) {
answersInArr=[qwa.answersMArray objectAtIndex:i];
if([answersInArr.MessageId isEqualToString:message.MessageId])
{
break;
}
}
AnswerMultipleCell * cell = (AnswerMultipleCell *) [tableView dequeueReusableCellWithIdentifier:#"AnswerMultipleCell"];
if (cell == nil)
{
// NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AnswerCustomCell" owner:self options:nil];
// cell = (AnswerCustomCell*)[nib objectAtIndex:0];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AnswerMultipleCell" owner:self options:nil];
cell = (AnswerMultipleCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//answer here goes
cell.answerTxt.text=answersInArr.Message;
cell.userName.text=answersInArr.SenderName;
[cell.answerTxt flashScrollIndicators];
//question
NSLog(#"%#",message.MessageId);
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
[cell.userPic setImage:[UIImage imageNamed:#"updateProfileIco.png" ]];
// [cell.quePic setImage:[UIImage imageNamed:#"updateProfileIco.png" ]];
//if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
avatar= [(AppDelegate *)[[UIApplication sharedApplication]delegate] getAvatar:[qwa.attendeIDMArray objectAtIndex:i] andAttendeEmail:[qwa.attendeEmails objectAtIndex:i]];
NSLog(#"----------:: %# == %# and message:%#",message.AttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
// cell.ansPic.image = [MainManager getSharedInstance].userManager.userImage;
cell.userPic.image = avatar;
// }
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.QuestionID);
// {
NSLog(#"------------:: %# == %# and message:%#",message.questionAttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
// cell.quePic.image = [MainManager getSharedInstance].userManager.userImage;
// cell.quePic.image = avatar;
// }
//}//end answersArray
return cell;
}
else {
//show question cell
QuestionCustomCell * cell = (QuestionCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"QuestionCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"QuestionCustomCell" owner:self options:nil];
cell = (QuestionCustomCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
cell.lblSaid.text =#"Asked";
cell.lblName.text =message.SenderName;
NSLog(#"Question is %#", message.question);
cell.lblText.text =message.Message;
[cell.lblText flashScrollIndicators];
// cell.lblAnswerQuestion.hidden = NO;
if (!message.answered) {
cell.lblAnswerQuestion.hidden = NO;
cell.userInteractionEnabled = YES;
}else {
cell.lblAnswerQuestion.hidden = YES;
cell.userInteractionEnabled = NO;
}
// cell.userInteractionEnabled = YES;
[[HMMainManager getSharedInstance].currentMeeting.questionDict setObject:message.AttendeeID forKey:message.MessageId];
NSLog(#"manager strID: %# ques cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
[cell.imgThumbUserPic setImage:[UIImage imageNamed:#"updateProfileIco.png"]];
// if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
// cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
cell.imgThumbUserPic.image = avatar;
// }
cell.tvAnswer.delegate = self;
NSMutableString* finalSec = [NSString stringWithFormat:#"%d",indexPath.section];
for (NSInteger x=0; x<3; x++) {
if (finalSec.length <3) {
finalSec = [NSString stringWithFormat:#"0%#",finalSec];
}
}
NSLog(#"%#", finalSec);
NSString* tag = [NSString stringWithFormat:#"%d%#",indexPath.row+1, finalSec];
NSLog(#"tag value %d",[tag intValue]);
cell.btnAnswer.tag = [tag intValue];//indexPath.row + 1000 + indexPath.section;
cell.tvAnswer.tag = [tag intValue];
cell.selectionStyle = UITableViewCellEditingStyleNone;
[cell.btnAnswer addTarget:self action:#selector(answerButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
// [message release];
return cell;
}
}
// [message release];
return nil;
}
If you have custom (non 44 point height) cells, then you need to implement - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

getting wrong value in custom uitableViewCell

Hello all I am implementing a chat Messenger. i am facing a strange situation. I have a custom tableview cell it works perfectly fine when i scroll normally. But if i scroll very fast like a crazy man the images of users get mixed. I cannot figure put what can be the reason any help fellows and thx in advance
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *rung;
if (indexPath.row%2 == 0) {
// 0.662745 0.662745 0.662745
rung=[UIColor colorWithRed:0.802745 green:0.802745 blue:0.802745 alpha:1];
color=NO;
}
else {
// 0.972549 0.972549 1
//0.411765 0.411765 0.411765
rung=[UIColor colorWithRed:0.862745 green:0.862745 blue:0.862745 alpha:1];
color=YES;
}
//static NSString *MyIdentifier = #"Identifier";
NSLog(#"====IndexPath is %d",indexPath.row);
ChatSlideDC *slide = [[HMMainManager getSharedInstance].currentMeeting.resumedChatMessages objectAtIndex:indexPath.section];
ChatMessageDC *message;
message = [[slide ChatMessageArray]objectAtIndex:indexPath.row];
NSLog(#"====Message Type is %#",message.MessageType);
NSLog(#"%#",message.Message);
if ([message.MessageType isEqualToString: #"0"] || [message.MessageType isEqualToString:#"1"]) {
ChatCustomCell * cell = (ChatCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"ChatCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ChatCustomCell" owner:self options:nil];
cell = (ChatCustomCell*)[nib objectAtIndex:0];
}
// cell.backgroundImage.backgroundColor=rung;
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//cell.backgroundColor=rung;
cell.lblSaid.text =#"Said";
cell.lblName.text =message.SenderName;
cell.lblText.text =message.Message;
NSLog(#"manager strID: %# chat cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
NSLog(#"%# == %#",message.AttendeeID,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID);
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
}
cell.selectionStyle = UITableViewCellEditingStyleNone;
// [message release];
return cell;
}
if ([message.MessageType isEqualToString:#"2"] || [message.MessageType isEqualToString:#"3"] ) {
if ([message.MessageType isEqualToString:#"3"] || (message.question && [message.question length]>0)) {
//show asnwer cell
AnswerCustomCell * cell = (AnswerCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"AnswerCustomCell"];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AnswerCustomCell" owner:self options:nil];
cell = (AnswerCustomCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//answer here goes
cell.answerdBy.text = message.SenderName;
cell.answerText.text = message.Message;
[cell.answerText flashScrollIndicators];
//question
cell.questionedBy.text = message.QuestionBy;
cell.questionText.text = message.question;
[cell.questionText flashScrollIndicators];
NSLog(#"%#",message.MessageId);
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
// if ([message.SenderName isEqualToString:compName] ) {
NSLog(#"----------:: %# == %# and message:%#",message.AttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
cell.ansPic.image = [MainManager getSharedInstance].userManager.userImage;
// }
}
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.QuestionID);
// NSString *qustWalaID=[[HMMainManager getSharedInstance].currentMeeting.questionDict objectForKey:message.QuestionID];
// NSLog(#"%#",questionDict);
if ([message.questionAttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID])
{
// if ([message.QuestionBy isEqualToString:compName] ) {
NSLog(#"------------:: %# == %# and message:%#",message.questionAttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
cell.quePic.image = [MainManager getSharedInstance].userManager.userImage;
// }
}
// tempChatMessageDC=message;
// tempAnswerCustomCell=cell;
// [message release];
return cell;
}
else {
//show question cell
QuestionCustomCell * cell = (QuestionCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"QuestionCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"QuestionCustomCell" owner:self options:nil];
cell = (QuestionCustomCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
cell.lblSaid.text =#"Asked";
cell.lblName.text =message.SenderName;
NSLog(#"Question is %#", message.question);
cell.lblText.text =message.Message;
[cell.lblText flashScrollIndicators];
// cell.lblAnswerQuestion.hidden = NO;
if (!message.answered) {
cell.lblAnswerQuestion.hidden = NO;
cell.userInteractionEnabled = YES;
}else {
cell.lblAnswerQuestion.hidden = YES;
cell.userInteractionEnabled = NO;
}
// cell.userInteractionEnabled = YES;
[[HMMainManager getSharedInstance].currentMeeting.questionDict setObject:message.AttendeeID forKey:message.MessageId];
NSMutableDictionary *tmpDoct=[HMMainManager getSharedInstance].currentMeeting.questionDict ;
// [questionDict setObject:message.AttendeeID forKey:message.MessageId];
NSLog(#"%#",tmpDoct );
NSLog(#"manager strID: %# ques cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
}
cell.tvAnswer.delegate = self;
NSMutableString* finalSec = [NSString stringWithFormat:#"%d",indexPath.section];
for (NSInteger x=0; x<3; x++) {
if (finalSec.length <3) {
finalSec = [NSString stringWithFormat:#"0%#",finalSec];
}
}
NSLog(#"%#", finalSec);
NSString* tag = [NSString stringWithFormat:#"%d%#",indexPath.row+1, finalSec];
NSLog(#"tag value %d",[tag intValue]);
cell.btnAnswer.tag = [tag intValue];//indexPath.row + 1000 + indexPath.section;
cell.tvAnswer.tag = [tag intValue];
cell.selectionStyle = UITableViewCellEditingStyleNone;
[cell.btnAnswer addTarget:self action:#selector(answerButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
// [message release];
return cell;
}
}
// [message release];
return nil;
}
You should correctly use cell's reusing. You have code fragment:
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
}
There is you don't process other variants. You should set user pic in any case
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
} else {
cell.imgThumbUserPic.image = nil; //or set it with another image
}

UITableView Data insertion

I have a problem on uitableview,
I have taken 3 sections in grouped table,
Inserted data for each section by using indexPath.section all is well but 3rd section is filled with both 1st and 2nd section data,
How to remove that data and how to fill my own data means separate data?
Code is:-
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (section == 0) {
return #"Product Details";
}
if (section == 1) {
return #"Ingredients";
}
if (section == 2) {
return #"My Allergies";
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
return 150;
}
if (indexPath.section == 1) {
return 100;
}
if (indexPath.section==2) {
return 45;
}
return 0;
}
- (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];
}
NSMutableString *redStr1 =[[NSMutableString alloc] initWithString:#"No" ];
NSMutableString *yellowStr1 =[[NSMutableString alloc] initWithString:#"No" ];
NSMutableString *greenStr1 =[[NSMutableString alloc] initWithString:#"No" ];
int a = [appDelegate.reIndex intValue];
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [appDelegate.ProductArray objectAtIndex:a];
// NSMutableString *str = [aDict1 objectForKey:#"IngredientInfo"];
NSMutableArray *array =[aDict1 objectForKey:#"IngredientInfo1"];
NSMutableString *nameStr = [[NSMutableString alloc] init];
NSMutableString *nameClr = [[NSMutableString alloc] init];
for (int s=0; s<[array count]; s++) {
NSDictionary *nameDict = [array objectAtIndex:s];
[nameStr appendString:[nameDict objectForKey:#"Name"]];
nameClr = [nameDict objectForKey:#"HalaStatus"];
if ([nameClr isEqualToString:#"Red"]) {
[redStr1 setString:#"Yes"];
}
if ([nameClr isEqualToString:#"Yellow"]) {
[yellowStr1 setString:#"Yes"];
}
if ([nameClr isEqualToString:#"Green"]) {
[greenStr1 setString:#"Yes"];
}
if (s == [array count]-1) {
[nameStr appendFormat:#"."];
}
else {
[nameStr appendFormat:#","];
}
}
if (indexPath.section == 0)
{
cell.userInteractionEnabled =NO;
imgview1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"images (1).jpg"] ];
[imgview1 setFrame:CGRectMake(12, 2, 100, 145)];
[cell addSubview:imgview1];
[imgview1 release];
imgview = [[UIImageView alloc]initWithFrame:CGRectMake(255,2 , 50, 45)];
[cell addSubview:imgview];
if ([redStr1 isEqualToString:#"Yes"]) {
[imgview setImage:[UIImage imageNamed:#"Red.png"]];
}
if ([redStr1 isEqualToString:#"No"] && [yellowStr1 isEqualToString:#"Yes"] ) {
[imgview setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if ([redStr1 isEqualToString:#"No"] && [yellowStr1 isEqualToString:#"No"] && [greenStr1 isEqualToString:#"Yes"]) {
[imgview setImage:[UIImage imageNamed:#"Green.png"]];
}
}
if (indexPath.section == 1) {
UITextView *textview1;
textview1 =[[UITextView alloc]initWithFrame:CGRectMake(12, 2, 294, 96)];
textview1.text = nameStr;
textview1.editable =NO;
[textview1 setFont:[UIFont systemFontOfSize:15]];
[cell addSubview:textview1];
}
if (indexPath.section == 2) {
cell.textLabel.text = [arr objectAtIndex:indexPath.row];
}
return cell;
}
if you have an array and access this in cellForRowAtIndexPath: with indexPath.row you will get for all sections the same lets say three elements.
What you have to do is an array inside an array:
Level 1 Section 1
Level 2 Row 1
Level 2 Row 2
Level 2 Row 3
Level 1 Section 2
Level 2 Row 1
Level 2 Row 2
Level 1 Section 3
Level 2 Row 1
Level 2 Row 2
Level 2 Row 3

Resources