uitableviewcells are overlapping first 2 cells of 3 overlap - ios

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

Related

After setting selectedBackgroundView of UITableViewCell when the cell is selected, background color of other components get changed

Due to some permission issue, in my tableView some cell can be selected by user and some cell can't be selected by that user. What I did in my cellForRowAtIndexPath is:
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
int row = (int)[indexPath row];
static NSString *simpleTableIdentifier = #"EditProjectTableCell";
Project* project = (Project*)[self.projectList objectAtIndex:row];
EditProjectTableCell *cell = (EditProjectTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:simpleTableIdentifier owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.serial.layer.cornerRadius = 5;
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:#"accessory_right.png"]];
cell.cellView.backgroundColor = [UIColor blackColor];
cell.backgroundColor = [UIColor blackColor];
}
if ([project.role isEqualToString:#"1"] || [project.role isEqualToString:#"2"]) {
UIView *customView = [[UIView alloc] initWithFrame:cell.frame];
customView.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = customView;
}
else cell.selectionStyle = UITableViewCellSelectionStyleNone;
if(cell.imageFetchOperation != nil) [cell.imageFetchOperation cancel];
cell.imageFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:YES
andFetchReportCounter:NO
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
if(cell.counterFetchOperation != nil) [cell.counterFetchOperation cancel];
cell.counterFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:NO
andFetchReportCounter:YES
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
cell.projectName.text = project.name;
cell.projectNumber.text = project.number;
cell.owner.text = [NSString stringWithFormat:#"%# %#",project.ownerName,project.ownerLastName];
NSString* temp_date = [Utils stringFromDateForGUI:project.creationDate];
cell.date.text = temp_date;
[cell.syncStatusView setImage:[Utils getImageForSyncStatus:project.isDirty.intValue]];
NSNumber *ret = [self.reportCountList objectForKey:project.pkId];
if(ret == nil) {
cell.serial.text = #"";
[cell.counterFetchOperation setPkId:project.pkId];
[self.tableCellUpdateQueue addOperation:cell.counterFetchOperation];
} else {
cell.serial.text = [NSString stringWithFormat:#"%d",[ret intValue]];
}
id img = [self getSmallImage:project.pkId andIndexPath:indexPath andCell:cell];
if(img == nil || img == (id)[NSNull null]) {
img = [UIImage imageNamed:#"gray-img.jpg"];
cell.iconImageView.image = [UIImage imageNamed:#"project-icon.png"];
cell.iconImageView.hidden = NO;
} else {
cell.iconImageView.hidden = YES;
}
cell.imageView.image = (UIImage*)img;
if ([project.role isEqualToString:#"2"] || [project.role isEqualToString:#"1"])
cell.selectImageView.hidden = NO;
else
cell.selectImageView.hidden = YES;
return cell;
}
Selection part is working just fine. But if a cell is selected then the background color of a UILabel gets changed to clear color. See the below images for clear idea.
Before selection:
After Selection :

how to plus and minus when button is clicked in uitabelview row and section and reload like foodpanda

I am creating app link food panda.let me explain the flow.I have a vc with table with rows and sections when i click on section it will expand and collapsing rows.in the section there is add button in each rows.wqhen i click on add button in section 3 row the button should hide and + and - button should show like the image given below.
2.when i click on the pluse and minus button it should add to cart and money should increase and decrease amount in cart i used below code for expand and collapse sections.
#implementation menulistingVC
- (void)viewDidLoad {
[super viewDidLoad];
[super viewDidLoad];
menuarray=[[NSMutableArray alloc]init];
arrselectedrow=[[NSMutableArray alloc]init];
defaults = [NSUserDefaults standardUserDefaults];
apiCall = [[APICall alloc]init];
isMultipleExpansionAllowed = NO;
arrSelectedSectionIndex = [[NSMutableArray alloc] init];
if (!isMultipleExpansionAllowed) {
[arrSelectedSectionIndex addObject:[NSNumber numberWithInt:countt+20]];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loadtable:)
name:#"array" object:nil];
_tblview.estimatedRowHeight = 69;
_tblview.rowHeight = UITableViewAutomaticDimension;
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)loadtable:(NSNotification*)notification
{
isMultipleExpansionAllowed = NO;
arrSelectedSectionIndex = [[NSMutableArray alloc] init];
if (!isMultipleExpansionAllowed) {
[arrSelectedSectionIndex addObject:[NSNumber numberWithInt:countt+20]];
}
[self getingfooddeatilsbacedonclub:[notification object]];
}
-(void)getingfooddeatilsbacedonclub:(NSString *)typestr{
_clubstr = [[NSUserDefaults standardUserDefaults]
stringForKey:#"newclubid"];
// accessToken=[defaults valueForKey:#"accessToken"];
// clubberId = [defaults valueForKey:#"idClubber_dtls"];
if (![APICall hasNetwork])
{
[Util displayToastMessage:#"No internet connection"];
}else
{
[customBezelActivityView activityViewForView:self.view];
NSString *urlstr = [NSString stringWithFormat:#"%s/presignin/menu/list/category/by_venue?clubId=%#&type=%#",urlPath,_clubstr,typestr];
NSLog(#"getherd :%#",urlstr);
[apiCall getArrayFromApiwithstauscode:urlstr restfulType:kRestfulGet andUseContentType:NO withRequestBody:nil completionHandler:^(NSArray *result, NSInteger statuscodeint){
NSLog(#"classifieds List response:%#",result);
NSLog(#"statuscode List response:%ld",(long)statuscodeint);
if (statuscodeint==200) {
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
menuarray=[result mutableCopy];
isMultipleExpansionAllowed = NO;
if (!isMultipleExpansionAllowed) {
[arrSelectedSectionIndex addObject:[NSNumber numberWithInt:countt+20]];
}
[_tblview reloadData];
});
}else if (statuscodeint==401){
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
UIStoryboard *storyBoard =[UIStoryboard storyboardWithName:#"Main" bundle:nil];
SignInViewController *SignINViewController=[storyBoard instantiateViewControllerWithIdentifier:#"SignINViewController"];
[self presentViewController:SignINViewController animated:YES completion:nil];
});
}
}];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return menuarray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
{
NSArray *arr=[menuarray[section] valueForKey:#"menu"];
return arr.count;
}else{
return 0;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MenudetailsTblCell";
menudetailscell = ( MenudetailsTblCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (menudetailscell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenudetailsTblCell" owner:self options:nil];
menudetailscell = [nib objectAtIndex:0];
}
if (menudetailscell == nil)
{
menudetailscell = [[MenudetailsTblCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
menudetailscell.detailview.layer.cornerRadius = 3.0;
menudetailscell.detailview.layer.masksToBounds = YES;
if (indexPath.row==0) {
menudetailscell.toplbl.hidden=YES;
}else{
menudetailscell.toplbl.hidden=NO;
}
menudetailscell.addbtntocart.layer.cornerRadius = 5.0;
menudetailscell.addbtntocart.layer.masksToBounds = YES;
menudetailscell.addbtntocart.tag=indexPath.row;
menudetailscell.plusebtn.tag=indexPath.row;
menudetailscell.minusbtn.tag=indexPath.row;
menudetailscell.plusebtn.hidden=YES;
menudetailscell.minusbtn.hidden=YES;
menudetailscell.noofitemslbl.hidden=YES;
NSArray *arr=[menuarray[indexPath.section] valueForKey:#"menu"];
menudetailscell.typelbl.text=[[arr objectAtIndex:indexPath.row]valueForKey:#"name"];
menudetailscell.describtionlbl.text=[[arr objectAtIndex:indexPath.row]valueForKey:#"description"];
NSString *cost=[NSString stringWithFormat:#"%#%#",[[arr objectAtIndex:indexPath.row]valueForKey:#"price"],#".00"];
NSString *imgid=[NSString stringWithFormat:#"%#",[[arr objectAtIndex:indexPath.row]valueForKey:#"idmenus"]];
NSString *tax=[NSString stringWithFormat:#"%#",[[arr objectAtIndex:indexPath.row]valueForKey:#"tax"]];
if ([tax isEqualToString:#"tax"]) {
menudetailscell.taxlbl.text=#"(*Inclusive of all taxes)";
}else{
menudetailscell.taxlbl.text=#"(*Exclusive of all taxes)";
}
menudetailscell.ratelbl.text=[NSString stringWithFormat:#"%# %#",[[arr objectAtIndex:indexPath.row]valueForKey:#"country"],cost];
[ menudetailscell.addbtntocart addTarget:self action:#selector(addbtnclicked:)forControlEvents:UIControlEventTouchUpInside];
NSString *typeimgUrl1 = [NSString stringWithFormat:#"%s/presignin/menu/showMedia?idMenu=%#",urlPath,imgid];
NSURL *imageURL=[NSURL URLWithString:typeimgUrl1];
menudetailscell.imgview.imageURL=imageURL;
[menudetailscell.plusebtn addTarget:self action:#selector(pluseTapShowHideSection:) forControlEvents:UIControlEventTouchUpInside];
[menudetailscell.minusbtn addTarget:self action:#selector(minusTapShowHideSection:) forControlEvents:UIControlEventTouchUpInside];
menudetailscell.selectionStyle = UITableViewCellSelectionStyleNone;
return menudetailscell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
static NSString *CellIdentifier = #"Menusectioncell";
menusectioncell = ( Menusectioncell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (menusectioncell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Menusectioncell" owner:self options:nil];
menusectioncell = [nib objectAtIndex:0];
}
if (menusectioncell == nil)
{
menusectioncell = [[Menusectioncell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
{
// right-arrow //down-arrow
menusectioncell.Sectiomtitlebtn.selected = YES;
menusectioncell.dotlbl.hidden=NO;
menusectioncell.expandtypeimg.image=[UIImage imageNamed:#"down-arrow"];
}
else{
menusectioncell.dotlbl.hidden=YES;
menusectioncell.expandtypeimg.image=[UIImage imageNamed:#"right-arrow"];
}
menusectioncell.Sectiomtitlebtn.tag=section;
menusectioncell.dotlbl.layer.cornerRadius = menusectioncell.dotlbl.frame.size.height/2;
menusectioncell.dotlbl.layer.masksToBounds = YES;
[menusectioncell.Sectiomtitlebtn addTarget:self action:#selector(btnTapShowHideSection:) forControlEvents:UIControlEventTouchUpInside];
NSString *btntitle=[menuarray[section] valueForKey:#"catagory"];
itemarr=[menuarray[section] valueForKey:#"menu"];
NSString *items=[itemarr[0] valueForKey:#"name"];
menusectioncell.sectiontitleilb.text=btntitle;
if (itemarr.count==1) {
menusectioncell.itemslbl.text=[NSString stringWithFormat:#"%#",items];
}else{
NSString *seconditemstr=[itemarr[1] valueForKey:#"name"];
menusectioncell.itemslbl.text=[NSString stringWithFormat:#"%#,%# etc..",items,seconditemstr];
}
menusectioncell.selectionStyle = UITableViewCellSelectionStyleNone;
return menusectioncell.contentView;
}
-(IBAction)btnTapShowHideSection:(UIButton*)sender
{
int section=sender.tag;
if (!sender.selected)
{
//originallcode
if (!isMultipleExpansionAllowed) {
[arrSelectedSectionIndex addObject:#"-1"];
[arrSelectedSectionIndex replaceObjectAtIndex:0 withObject:[NSNumber numberWithInteger:sender.tag]];
}else {
NSLog(#"%#",arrSelectedSectionIndex);
[arrSelectedSectionIndex addObject:[NSNumber numberWithInteger:sender.tag]];
}
menusectioncell.dotlbl.hidden=YES;
menusectioncell.expandtypeimg.image=[UIImage imageNamed:#"right-arrow"];
sender.selected = YES;
}
else{
sender.selected = NO;
menusectioncell.dotlbl.hidden=NO;
menusectioncell.expandtypeimg.image=[UIImage imageNamed:#"down-arrow"];
if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:sender.tag]])
{
[arrSelectedSectionIndex removeObject:[NSNumber numberWithInteger:sender.tag]];
}
}
if (!isMultipleExpansionAllowed) {
[_tblview reloadData];
}else {
[_tblview reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
- (void)addbtnclicked:(UIButton *)sender
{
menudetailscell.plusebtn.hidden=NO;
menudetailscell.minusbtn.hidden=NO;
menudetailscell.noofitemslbl.hidden=NO;
menudetailscell.addbtntocart.hidden=YES;
int rowselect=sender.tag;
[arrselectedrow addObject:[NSNumber numberWithInteger:sender.tag]];
NSIndexPath* indexPath1 = [NSIndexPath indexPathForRow:sender.tag inSection:sectionselect];
[self.tblview beginUpdates];
[self.tblview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tblview endUpdates];
}
- (void)pluseTapShowHideSection:(UIButton *)sender
{
}
- (void)minusTapShowHideSection:(UIButton *)sender
{
if ([arrselectedrow containsObject:[NSNumber numberWithInteger:sender.tag]])
{
[arrselectedrow removeObject:[NSNumber numberWithInteger:sender.tag]];
}
[self.tblview beginUpdates];
[self.tblview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:arrselectedrow, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tblview endUpdates];
}

UItableview scrollsToTop is not working when click on button ios

I am having uicollection scrolling in horizontal direction , inside the collection view cell i have two table view - one _tablewView
-another _tblnoti , i have added a button for collapsing the order card , on click of that i want to scroll _tableView to the top , but its not working
on click of drop downbutton i m reloading the table view inside that
- (IBAction)btnDropdownclick:(UIButton*)sender
{
NSIndexPath *indesss = [NSIndexPath indexPathForItem:sender.tag-300 inSection:0];
CollectionViewCell *cell = (CollectionViewCell*) [_InnercollectionView cellForItemAtIndexPath:indesss];
_flag =indesss.item;
shouldCellBeExpanded = !shouldCellBeExpanded;
if(shouldCellBeExpanded)
{
[sender setImage:[UIImage imageNamed:#"uparrow.png"] forState:UIControlStateNormal];
}
else
{
[sender setImage:[UIImage imageNamed:#"downarrow.png"] forState:UIControlStateNormal];
}
cell.shouldCellBeExpanded = !cell.shouldCellBeExpanded ;
[_InnercollectionView performBatchUpdates:^{
[cell.tabelView reloadData];
} completion:^(BOOL finished) {
}];
}
below is code in cell class
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(_shouldCellBeExpanded){
_heightcheckview.constant = _tabelView.contentSize.height+120;
_tblheight.constant = _tabelView.contentSize.height+20;
}
else
{
_tabelView.scrollsToTop = YES;
_heightcheckview.constant = 195;
_tblheight.constant = 105;
}
if (tableView == _tblNoti) {
static NSString *MyIdentifier = #"noticell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
// self.tblheight .constant = tableView.contentSize.height;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] ;
}
// FoodDescModalClass *orderDataTypess;
if(!(self.arrayforNoti.count == 0))
{
NSDictionary *diction = [self.arrayforNoti objectAtIndex:indexPath.row];
UILabel *lbl = (UILabel*)[cell.contentView viewWithTag:2345];
lbl.text = [diction valueForKey:#"data"];
}
return cell;
}
else if (tableView == _tabelView){
static NSString *MyIdentifier = #"maineecell";
CollTableViewCell *cells = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
// self.tblheight .constant = tableView.contentSize.height;
if (cells == nil)
{
cells = [[CollTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] ;
}
if(_havecomment)
{
if(indexPath.row == self.arrayforitems.count)
{
UITableViewCell* celld = [tableView dequeueReusableCellWithIdentifier:#"commentcell"];
UILabel *lblcomment = [celld.contentView viewWithTag:4545];
lblcomment.text = _finalcomment;
lblcomment.layer.borderWidth = 1.0f ;
lblcomment.layer.cornerRadius = 4.0f ;
lblcomment.layer.masksToBounds = YES;
return celld;
}else{
NSDictionary*dict = [self.arrayforitems objectAtIndex:indexPath.row];
cells.lblName.text= [dict valueForKey:#"item"];
cells.lblPrice.text = [dict valueForKey:#"price"];
cells.lblquantity.text = [dict valueForKey:#"qty"];
NSString*type = [dict valueForKey:#"type"];
if([type isEqualToString:#"1"])
{
cells.imgveg.image=[UIImage imageNamed:#"veg"];
}
else if([type isEqualToString:#"2"])
{
cells.imgveg.image=[UIImage imageNamed:#"nonveg"];
}
else
{
cells.imgveg.image=[UIImage imageNamed:#"drink.png"];
}
cells.lblquantity.layer.borderWidth = 1.0f ;
cells.lblquantity.layer.cornerRadius = 4.0f ;
cells.lblquantity.layer.masksToBounds = YES;
}
}
else{
NSDictionary*dict = [self.arrayforitems objectAtIndex:indexPath.row];
cells.lblName.text= [dict valueForKey:#"item"];
cells.lblPrice.text = [dict valueForKey:#"price"];
cells.lblquantity.text = [dict valueForKey:#"qty"];
NSString*type = [dict valueForKey:#"type"];
if([type isEqualToString:#"1"])
{
cells.imgveg.image=[UIImage imageNamed:#"veg"];
}
else if([type isEqualToString:#"2"])
{
cells.imgveg.image=[UIImage imageNamed:#"nonveg"];
}
else
{
cells.imgveg.image=[UIImage imageNamed:#"drink.png"];
}
cells.lblquantity.layer.borderWidth = 1.0f ;
cells.lblquantity.layer.cornerRadius = 4.0f ;
cells.lblquantity.layer.masksToBounds = YES;
}
return cells;
}
else
{
return nil;
}}
screen shots are below
follow in sequence
http://prntscr.com/du4p2f
http://prntscr.com/du4p00
http://prntscr.com/du4q1t

Two different UICollectionViewCell in same UICollectionView

I'm trying to put two different UICollectionViewCells in one UICollectionView. It's working, but after some scrolls, I receive memory warnings and the app crashes.
Here is my code:
Create and fill the cells:
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"KatalogBAGCell";
BAGCell *cell = (BAGCell*)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
id unknown = [[self.katalogBAGs objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
BAGObject* bag = nil;
SerienObject* serie = nil;
NSString *filePath;
if ([unknown isKindOfClass:[SerienObject class]]) {
serie = (SerienObject*)unknown;
cell = nil;
cell = [[BAGCell alloc] initWithSerie:serie.serienID];
filePath = serie.completePath;
cell.bagText.text = serientext;
cell.directText.text = serie.serienName;
[cell.directText sizeToFit];
}
else {
bag = (BAGObject*)unknown;
if ( [self isEmptyCell:bag.fileName] ) {
cell.alpha = 0.0;
cell.hidden = cell.contentView.hidden = YES;
return cell;
}
else {
cell.alpha = 1.0;
cell.hidden = cell.contentView.hidden = NO;
// should be a real bag
if (self.viewMode==0) {
// regular floating mode
cell.fullscreenButton.hidden = NO;
[cell.bookmarkButton addTarget:self action:#selector(createBookMarkForThisBAG:) forControlEvents:UIControlEventTouchUpInside];
[cell.fullscreenButton addTarget:self action:#selector(pushToFullScreenView:) forControlEvents:UIControlEventTouchUpInside];
}
else if (self.viewMode==1) {
// fullscreen mode
cell.fullscreenButton.hidden = YES;
[cell.bookmarkButton addTarget:self action:#selector(createBookMarkForThisBAG:) forControlEvents:UIControlEventTouchUpInside];
}
filePath = bag.completePath;
// clear the reused cell
for (UIView *v in [cell.directOrderContainer subviews]) {
if ((UILabel*)v==cell.directText) {
continue;
}
[v removeFromSuperview];
}
if (SAMOADelegate.appIsInPresentationMode==NO) {
// generate the infos for the textInfoLine
NSString *artCols = #"a.vkpreis, a.ve, a.groesse, a.ausverkauft";
NSString *sqlStatement = [NSString stringWithFormat:#"SELECT %# FROM kataloge_bags_artikel as ba LEFT JOIN artikel as a ON a.artikel = ba.artikelnr where ba.bagid=%i order by ba.position_in_bag ASC", artCols, bag.bagID];
sqlite3_stmt *itemSQL;
NSString *lineText = #"";
int c = 0;
if(sqlite3_prepare_v2([ToolBox db], [sqlStatement UTF8String], -1, &itemSQL, NULL) == SQLITE_OK) {
while(sqlite3_step(itemSQL) == SQLITE_ROW) {
ArticleItem *item = [[ArticleItem alloc] init];
item.vkpreis = [[NSDecimalNumber alloc] initWithFloat:[self.helper calculateArticlePriceforPrice:sqlite3_column_double(itemSQL, 0)]];
item.verpackungseinheit = sqlite3_column_int(itemSQL, 1);
item.sizeInCM = [ToolBox convertFloatToString:sqlite3_column_double(itemSQL, 2)];
item.ausverkauft = [ToolBox checkNullString:(char *)sqlite3_column_text(itemSQL, 3)];
NSString *trenner = #"";
if (c!=0) {
trenner = #" ยท ";
}
if (item.ausverkauft.length!=0) {
// ausverkauft
NSString *price = [NSString stringWithFormat:#"- %#", SAMOADelegate.loggedInCustomer.waehrungsZeichen];
NSString *part = [NSString stringWithFormat:#"%#%# %#:%i %# %#", trenner, price, veText, item.verpackungseinheit, item.sizeInCM, cmText];
lineText = [lineText stringByAppendingString:part];
}
else {
// not ausverkauft
NSString *price = [ToolBox convertDecimalNumber: item.vkpreis withCurrencySymbol:SAMOADelegate.loggedInCustomer.waehrungsZeichen];
NSString *part = [NSString stringWithFormat:#"%#%# %#:%i %# %#", trenner, price, veText, item.verpackungseinheit, item.sizeInCM, cmText];
lineText = [lineText stringByAppendingString:part];
}
c++;
}
} else { [ToolBox logDatabaseError:_cmd]; } sqlite3_finalize(itemSQL);
bag.textInfoLine = lineText;
}
// check if this an article which you can order directly
if (bag.amountOfArticles==1) {
[self createDirectOrderViewForCell:cell andItem:bag];
[cell.directText setText:bag.marketingtext];
}
else {
cell.defaultContainer.hidden = NO;
cell.directOrderContainer.hidden = YES;
if (SAMOADelegate.appIsInPresentationMode==YES) {
[cell.bagText setText:bag.marketingtext];
}
else {
[cell.bagText setText:bag.textInfoLine];
}
}
if (bag.isBookMarked==YES) {
[cell.bookmarkButton setImage:[UIImage imageNamed:#"bookmark-icon-active.png"] forState:UIControlStateNormal];
}
else {
[cell.bookmarkButton setImage:[UIImage imageNamed:#"bookmark-icon-inactive.png"] forState:UIControlStateNormal];
}
if (SAMOADelegate.appIsInPresentationMode==YES) {
cell.bookmarkButton.hidden = YES;
}
// check if this bag is already in the cart
int artInCart = [ToolBox returnSQLCountForQuery:[NSString stringWithFormat:#"SELECT COUNT(*) FROM auftragsposition where auftragsnr = '%i' AND bagid = '%i' LIMIT 1", SAMOADelegate.currentOrder.belegnr, bag.bagID]];
if (artInCart) {
cell.isInCartStateView.image = [UIImage imageNamed:#"ordered-dot.png"];
}
else {
cell.isInCartStateView.image = [UIImage imageNamed:#"not-ordered-dot.png"];
}
self.lastLoadedBagIs = bag.bagID;
self.latestLoadedIndex = indexPath.row;
}
}
__weak UIActivityIndicatorView *iV = cell.loadingIndicator;
[cell.loadingIndicator startAnimating];
[cell.bagImageView setImageWithURL:[NSURL fileURLWithPath:filePath]
placeholderImage:nil
options:0
progress:^(NSUInteger receivedSize, long long expectedSize) { [iV startAnimating]; }
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { [iV stopAnimating];
}];
//rounded corners for the cell
[self roundedCornersForLayerinCell:cell.bagImageView.layer];
[cell.bagImageView.layer setShadowPath:[[UIBezierPath bezierPathWithRoundedRect:cell.frame cornerRadius:cell.layer.cornerRadius] CGPath]];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = cell.bounds;
maskLayer.path = maskPath.CGPath;
// Set the newly created shape layer as the mask for the image view's layer
cell.layer.mask = maskLayer;
return cell;
}
and cell object *.m:
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"BAG-Template-1" owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
and secondary init cell:
-(id)initWithSerie:(int)serienID {
self = [super init];
if (self) {
if (serienID>0) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"BAG-Template-2" owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
else {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"BAG-Template-1" owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
}
return self;
}
Any idea why I receive memory warnings?

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
}

Resources