Rows of Level 1 should expand and collapse. Suppose if Row 0 is open - that means its status is 1 - and next row's status is 0, if I click on next row whose status is 0, then the row whose status is 1 should get closed.
How can I do that?
Here is my code:
- (void)viewDidLoad {
[super viewDidLoad];
dictBtnStatus = [[NSMutableDictionary alloc] init];
arraylist = [[NSMutableArray alloc] init];
array5 = [[NSMutableArray alloc] init];
array1 = [[NSMutableArray alloc] init];
objects = #[#"Medical Services In Chicago", #"Medical Services On Campus", #"ABC", #"California"];
// objects = #[#"Medical Services In Chicago", #"Medical Services On Campus"];
arrObjectValueChicago = #[#"Ronald McDonald® Children's Hospital of Loyola", #"Burn Centers", #"Gottlieb Hospitals"];
arrObjectValueCampus = #[#"Cardinal Bernardin Cancer Center1", #"Center for Heart & Vascular Medicine2", #"ABC"];
for (int i = 0; i < [arrObjectValueCampus count]; i++) {
dictListCampus1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"2", #"level",[arrObjectValueCampus objectAtIndex:i], #"name", nil];
[array5 addObject:dictListCampus1];
}
NSDictionary *dictListCampus = [[NSDictionary alloc] initWithObjectsAndKeys:#"Wellness Centers", #"name", #"1", #"level", array5, #"Objects", nil];
NSMutableArray *array6 = [[NSMutableArray alloc] initWithObjects:dictListCampus, nil];
array3 = [[NSMutableArray alloc] init ];
for (int i = 0; i < [arrObjectValueChicago count]; i++){
dictList3 = [[NSDictionary alloc]initWithObjectsAndKeys:#"2", #"level",[arrObjectValueChicago objectAtIndex:i], #"name", nil];
[array3 addObject:dictList3];
}
NSDictionary *dictList2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"Hospitals", #"name", #"1", #"level", array3, #"Objects", nil];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithObjects:dictList2, nil];
for (int i = 0; i < [objects count]; i++) {
if (i == 0) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:0], #"name", #"0", #"level", array2, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 1) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:1], #"name", #"0", #"level", array6, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 2) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:2], #"name", #"0", #"level", array6, #"Objects", nil];
[array1 addObject:dictionary];
} else {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:3], #"name", #"0", #"level", array2, #"Objects", nil];
[array1 addObject:dictionary];
}
}
dictList = [[NSDictionary alloc] initWithObjectsAndKeys:array1, #"Objects", nil];
arrayOriginal = [dictList valueForKey:#"Objects"];
[arraylist addObjectsFromArray:arrayOriginal];
}
#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arraylist count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// static NSString *CellIdentifier = #"CustomCellIdentifier";
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (IndentLevel == 0) {
CustomCellHeader *cell = (CustomCellHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellHeader" owner:self options:nil];
cell = self.headercell;
self.headercell = nil;
}
cell.lblHeader.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
NSLog(#"indexFor level 0 ::%# %d",cell.lblHeader.text,indexPath.row);
return cell;
} else if (IndentLevel == 1) {
CustomCellSubHeader *cell = (CustomCellSubHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (!cell) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellSubHeader" owner:self options:nil];
cell = self.subheadercell;
self.subheadercell = nil;
NSLog(#"dicbtn %#", dictBtnStatus);
NSString *strName = [[arraylist objectAtIndex:indexPath.row]valueForKey:#"name"];
NSString *str = [dictBtnStatus objectForKey:strName];
NSLog(#"indexFor level 1 ::%# %d", strName, indexPath.row);
if ([str isEqualToString:#"1"]) {
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
}
cell.lblSubHeader.text = strName;
cell.imgShadow.hidden = YES;
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
}
return cell;
} else if (IndentLevel == 2) {
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCell" owner:self options:nil];
cell = self.cells;
self.cells = nil;
}
cell.txtAddress.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell.btnCall addTarget:self action:#selector(btnCall:) forControlEvents:UIControlEventTouchUpInside];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
return cell;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tblist deselectRowAtIndexPath:indexPath animated:YES];
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
NSString *strName = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
CustomCellSubHeader *cell = ((CustomCellSubHeader*)[tblist cellForRowAtIndexPath:indexPath]);
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"0" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
}
NSDictionary *d = [arraylist objectAtIndex:indexPath.row];
if ([d valueForKey:#"Objects"]) {
NSArray *ar = [d valueForKey:#"Objects"];
BOOL isAlreadyInserted = NO;
for (NSDictionary *dInner in ar) {
NSInteger index = [arraylist indexOfObjectIdenticalTo:dInner];
isAlreadyInserted = (index > 0 && index != NSIntegerMax);
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"0" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
} else if (IndentLevel == 0) {
NSString *strStatus = [dictBtnStatus objectForKey:strName];
if ([strStatus isEqualToString:#"1"]) {
// NSDictionary *dict = [arraylist objectAtIndex:previousRow];
// if ([dict valueForKey:#"Objects"]) {
NSArray * array = [[arraylist objectAtIndex:previousRow]valueForKey:#"Objects"];
[self miniMizeThisRows:array];
}
}
if (isAlreadyInserted) break;
}
if (isAlreadyInserted) {
if ([arraylist count] - 1 && IndentLevel == 1) {
cell.imgShadow.hidden = NO;
}
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"0" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
} else if (IndentLevel == 0) {
[dictBtnStatus setValue:#"0" forKey:strName];
}
[self miniMizeThisRows:ar];
} else {
NSUInteger count=indexPath.row + 1;
NSMutableArray *arCells = [NSMutableArray array];
for (NSDictionary *dInner in ar) {
[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
previousRow = [indexPath row];
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"1" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
} else if (IndentLevel == 0) {
[dictBtnStatus setValue:#"1" forKey:strName];
}
[arraylist insertObject:dInner atIndex:count++];
}
[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger indentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (indentLevel == 0) {
return 40;
} else if (indentLevel == 1) {
return 25;
} else if (indentLevel == 2) {
CustomCell *cell = ((CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"]);
CGSize maximumSize = CGSizeMake(300, 9999);
UIFont *myFont = [UIFont fontWithName:#"Arial" size:11.5];
CGSize myStringSize = [cell.txtAddress.text sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
if (myStringSize.height > 80) {
myStringSize.height = 50;
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
cell.txtAddress.scrollEnabled = YES;
} else {
cell.txtAddress.scrollEnabled = YES;
myStringSize.height = 40;
}
return myStringSize.height+ 50;
} else return 25;
}
#pragma mark - TableAnimation
- (void)miniMizeThisRows:(NSArray *)ar {
for(NSDictionary *dInner in ar) {
NSUInteger indexToRemove = [arraylist indexOfObjectIdenticalTo:dInner];
NSArray *arInner = [dInner valueForKey:#"Objects"];
if (arInner && [arInner count] > 0) {
[self miniMizeThisRows:arInner];
}
if ([arraylist indexOfObjectIdenticalTo:dInner]!= NSNotFound) {
[arraylist removeObjectIdenticalTo:dInner];
[tblist deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexToRemove inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (void)viewDidLoad {
[super viewDidLoad];
dictBtnStatus = [[NSMutableDictionary alloc] init];
arraylist = [[NSMutableArray alloc] init];
array5 = [[NSMutableArray alloc] init];
array1 = [[NSMutableArray alloc] init];
objects = #[#"Medical Services In Chicago", #"Medical Services On Campus", #"ABC", #"California"];
// objects = #[#"Medical Services In Chicago", #"Medical Services On Campus"];
arrObjectValueChicago = #[#"Ronald McDonald® Children's Hospital of Loyola", #"Burn Centers", #"Gottlieb Hospitals"];
arrObjectValueCampus = #[#"Cardinal Bernardin Cancer Center1", #"Center for Heart & Vascular Medicine2", #"ABC"];
for (int i = 0; i < [arrObjectValueCampus count]; i++) {
dictListCampus1 = [[NSDictionary alloc]initWithObjectsAndKeys:#"2", #"level",[arrObjectValueCampus objectAtIndex:i], #"name", nil];
[array5 addObject:dictListCampus1];
}
NSDictionary *dictListCampus = [[NSDictionary alloc]initWithObjectsAndKeys:#"Wellness Centers", #"name", #"1", #"level", array5, #"Objects", nil];
NSMutableArray *array6 = [[NSMutableArray alloc] initWithObjects:dictListCampus, nil];
NSDictionary *dictListCampus2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"Wellness Centers123", #"name", #"1", #"level", array5, #"Objects", nil];
NSMutableArray *array61 = [[NSMutableArray alloc] initWithObjects:dictListCampus2, nil];
array3 = [[NSMutableArray alloc] init];
for (int i = 0; i < [arrObjectValueChicago count]; i++) {
dictList3 = [[NSDictionary alloc] initWithObjectsAndKeys:#"2", #"level",[arrObjectValueChicago objectAtIndex:i], #"name", nil];
[array3 addObject:dictList3];
}
NSDictionary *dictList2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"Hospitals", #"name", #"1", #"level", array3, #"Objects", nil];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithObjects:dictList2, nil];
for (int i = 0; i < [objects count]; i++) {
if (i == 0) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:0], #"name", #"0", #"level", array2, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 1) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:1], #"name", #"0", #"level", array6, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 2) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:2], #"name", #"0", #"level", array61, #"Objects", nil];
[array1 addObject:dictionary];
}
// else {
// dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:3], #"name", #"0", #"level", array2, #"Objects", nil];
// [array1 addObject:dictionary];
//}
}
dictList = [[NSDictionary alloc] initWithObjectsAndKeys:array1, #"Objects", nil];
NSLog(#"DictList :: %#", dictList);
arrayOriginal = [dictList valueForKey:#"Objects"];
NSLog(#"Array Original :: %#", arrayOriginal);
[arraylist addObjectsFromArray:arrayOriginal];
//[tblist.delegate tableView:tblist didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//[tblist.delegate tableView:tblist didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
}
#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arraylist count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//static NSString *CellIdentifier = #"CustomCellIdentifier";
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (IndentLevel == 0) {
CustomCellHeader *cell = (CustomCellHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellHeader" owner:self options:nil];
cell = self.headercell;
self.headercell = nil;
}
cell.lblHeader.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
NSLog(#"indexFor level 0 ::%# %d",cell.lblHeader.text, indexPath.row);
return cell;
} else if (IndentLevel == 1) {
CustomCellSubHeader *cell = (CustomCellSubHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (!cell) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellSubHeader" owner:self options:nil];
cell = self.subheadercell;
self.subheadercell = nil;
NSLog(#"dicbtn %#", dictBtnStatus);
}
NSString *strName = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
NSString *str = [dictBtnStatus objectForKey:strName];
NSLog(#"indexFor level 1 ::%# %d", strName, indexPath.row);
if ([str isEqualToString:#"1"]) {
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
}
// else {
// [cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
//}
cell.lblSubHeader.text = strName;
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
if (indexPath.row == arraylist.count - 1) {
cell.imgShadow.hidden = NO;
}
return cell;
} else if (IndentLevel == 2) {
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCell" owner:self options:nil];
cell = self.cells;
self.cells = nil;
}
cell.txtAddress.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell.btnCall addTarget:self action:#selector(btnCall:) forControlEvents:UIControlEventTouchUpInside];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
return cell;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCellSubHeader *cell;
if ([[tblist cellForRowAtIndexPath:indexPath] isKindOfClass:[CustomCellSubHeader class]]) {
cell = (CustomCellSubHeader*)[tblist cellForRowAtIndexPath:indexPath];
UIImage *img = [cell.btnarrow imageForState:UIControlStateNormal];
if ([img isEqual:[UIImage imageNamed:#"dwn1_arow.png"]]) {
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[dictBtnStatus setValue:#"0" forKey:cell.lblSubHeader.text];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
cell.imgShadow.hidden = NO;
} else {
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
dictBtnStatus = [[NSMutableDictionary alloc] init];
[dictBtnStatus setValue:#"1" forKey:cell.lblSubHeader.text];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
cell.imgShadow.hidden = YES;
}
}
NSMutableArray *arrIndex = [[NSMutableArray alloc] init];
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (IndentLevel == 0) {
arrLast = [[NSMutableArray alloc] init];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *d = [arraylist objectAtIndex:indexPath.row];
if ([d valueForKey:#"Objects"]) {
NSArray *ar = [d valueForKey:#"Objects"];
BOOL isAlreadyInserted = NO;
for (NSDictionary *dInner in ar) {
NSInteger index = [arraylist indexOfObjectIdenticalTo:dInner];
isAlreadyInserted = (index > 0 && index != NSIntegerMax);
if (isAlreadyInserted) break;
}
if (isAlreadyInserted) {
[self miniMizeThisRows:ar];
} else {
NSUInteger count = indexPath.row + 1;
NSMutableArray *arCells = [NSMutableArray array];
for (NSDictionary *dInner in ar) {
[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
[arrLast addObject:dInner];
[arraylist insertObject:dInner atIndex:count++];
}
[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationBottom];
}
}
//NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (IndentLevel == 0) {
NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];
for (int i = 0 ; i < arraylist.count; i++) {
NSDictionary *dic = [arraylist objectAtIndex:i];
if ([[dic valueForKey:#"level"] intValue] != 0) {
NSInteger index = [arrLast indexOfObjectIdenticalTo:dic];
if ((index >= 0 && index != NSIntegerMax)) {
} else {
[discardedItems addIndex:i];
[arrIndex addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
}
}
if (discardedItems.count > 0) {
[arraylist removeObjectsAtIndexes:discardedItems];
[tblist deleteRowsAtIndexPaths:arrIndex withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger indentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (indentLevel == 0) {
return 40;
} else if (indentLevel == 1) {
return 25;
} else if (indentLevel == 2) {
CustomCell *cell = ((CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"]);
CGSize maximumSize = CGSizeMake(300, 9999);
UIFont *myFont = [UIFont fontWithName:#"Arial" size:11.5];
CGSize myStringSize = [cell.txtAddress.text sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
if (myStringSize.height > 80) {
myStringSize.height = 50;
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
cell.txtAddress.scrollEnabled = YES;
} else {
cell.txtAddress.scrollEnabled = YES;
myStringSize.height = 40;
}
return myStringSize.height + 50;
} else return 25;
}
#pragma mark - TableAnimation
- (void)miniMizeThisRows:(NSArray *)ar {
for (NSDictionary *dInner in ar) {
NSUInteger indexToRemove = [arraylist indexOfObjectIdenticalTo:dInner];
NSArray *arInner=[dInner valueForKey:#"Objects"];
if (arInner && [arInner count] > 0) {
[self miniMizeThisRows:arInner];
}
if ([arraylist indexOfObjectIdenticalTo:dInner] != NSNotFound) {
[arraylist removeObjectIdenticalTo:dInner];
[tblist deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexToRemove inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
}
}
#pragma mark - Buttons
- (IBAction)btnCall:(id)sender {
UIAlertView *Notpermitted = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Do you want to call on this number." delegate:nil cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
Notpermitted.delegate = self;
[Notpermitted tag];
[Notpermitted show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *strCall = [NSString stringWithFormat:#"tel://999-999-9999"];
NSURL *url = [NSURL URLWithString:strCall];
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:url];
} else {
UIAlertView *Notpermitted = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
}
}
}
see following tutorial
http://www.cocoanetics.com/2011/03/expandingcollapsing-tableview-sections/
www.alexandre-gomes.com/?p=482
Expand/collapse section in UITableView in iOS
Related
I have an old project done by a developer some times ago.. This particular project has 3 collection views such as collectionAnnouncments, collectionNews and collectionBulletin.
The first collectionview collectionAnnouncments is loading a same cell 10 times. But other two sections loading the cell correctly one time as per the response count.
I don't have any idea up to now for this problem. I tried some solutions from the google but I couldn't sorted because of the bad UI and Code implementation by that developer.
Ex- He used one UICollectionView Inside a tableview and using UICollectionView Class for all 3 collectionview and used a general cell for all collectionviews.
declaration... in m file
__weak IBOutlet UITableView *table;
UICollectionView *collectionAnnouncments, *collectionBulletin,
*collectionNews;
Please check the following codes and provide me a better simple solution to fix this issue without any major modifications or re-implementation because I don't have time for that.
- (void)viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = NO;
home.title=[Utilities getLocalizedStringForKey:#"Home"];
[Utilities setNavigationController:self];
//self.label.text=NSLocalizedFailureReasonErrorKey
self.navigationItem.leftBarButtonItem = nil;
__block BOOL newsDone = NO, bulletInDone = NO, announcmentDone = NO, refreshed = NO;
collectionViewDic = [[NSMutableDictionary alloc]init];
[Utilities serverRequest:#{#"getNewsfeed":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
collectionViewDic[#"news"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_newsArray = dictionarys;
NSLog(#"news%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"nf_id" ascending:NO];
_sortednewsArray = [_newsArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted news Response -%#", _sortednewsArray);
//Registeriing the collectionview custom cell
// [UICollectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:#"customCell"];
// [collectionAnnouncments registerClass:[CustomCell class] forCellWithReuseIdentifier:#"customCell"];
// [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"Cell"];
newsDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
[Utilities serverRequest:#{#"getBulletin":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
// NSString *bulletinID = #"wb_id";
collectionViewDic[#"bulletin"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_bulletinArray = dictionarys;
NSLog(#"bulletin%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"wb_id" ascending:NO];
_sortedbulletinArray = [_bulletinArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted bulletin Response -%#", _sortedbulletinArray);
bulletInDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
[Utilities serverRequest:#{#"getAnnouncement":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
collectionViewDic[#"announcement"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_annArray = dictionarys;
NSLog(#"AnnouncementResponse%#",dictionarys);
NSLog(#" Ann ID%#", [dictionarys valueForKey:#"anc_id"]);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"date_added" ascending:NO];
_sortedAnnArray = [_annArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted Array Response -%#", _sortedAnnArray);
NSLog(#"Sorted Ann Array-count%zd",_sortedAnnArray.count);
NSLog(#"Sorted Ann ID%#", [_sortedAnnArray valueForKey:#"anc_id"]);
announcmentDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
menuView = [Utilities addMenuView:self];
}
-(void)getNewsFeed
{
collectionViewDic = [[NSMutableDictionary alloc]init];
[Utilities serverRequest:#{#"getNewsfeed":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
if(response != nil)
{
if ([response isKindOfClass:[NSString class]]) {
// print response .
NSLog(#"MAIN RESPONSE!%#",response);
}
//on successfully response, which provided dictionary,
else if ([[response objectForKey:#"success"] boolValue] == true) {
// on true print response data.
collectionViewDic[#"news"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_newsArray = dictionarys;
NSLog(#"news%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"nf_id" ascending:NO];
_sortednewsArray = [_newsArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted news Response -%#", _sortednewsArray);
}
//on success response, with failure message which is false.
else if ([[response objectForKey:#"success"] boolValue] == false) {
// handle error on success is false.
}
}
} errorBlock:nil];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#try {
NSString *key = #"";
if ([collectionView isEqual:collectionNews])
key = #"news";
else if ([collectionView isEqual:collectionAnnouncments])
key = #"announcement";
else if ([collectionView isEqual:collectionBulletin])
key = #"bulletin";
NSDictionary *mainDic = collectionViewDic[key];
NSArray *array = mainDic[ [mainDic allKeys][0] ];
return [array count];
} #catch (NSException *exception) {
return 0;
}
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
#try {
//NSString *key = #"";
if ([collectionView isEqual:collectionNews])
return _sortednewsArray.count;
else if ([collectionView isEqual:collectionAnnouncments])
return _sortedAnnArray.count;
else if ([collectionView isEqual:collectionBulletin])
return _sortedbulletinArray.count;
}
#catch (NSException *exception) {
return 0;
}
// return _sortedAnnArray.count + _sortednewsArray.count + _sortedbulletinArray.count;
// return [[collectionViewDic allKeys] count];
// return 50;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"generalCell" forIndexPath:indexPath];
// CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"customCell" forIndexPath:indexPath];
// cell.tag = indexPath.row;
[cell setTag:indexPath.row];
//UILabel *test = [cell.contentView viewWithTag:1];
UIImageView *image = [cell.contentView viewWithTag:1];
//UILabel *cellTitle = [cell.contentView viewWithTag:2];
//UILabel *cellHead =[cell.contentView viewWithTag:2];
if ([collectionView isEqual:collectionAnnouncments]) {
// NSDictionary *mainDic = collectionViewDic[#"announcement"];
// NSArray *array = mainDic[ [mainDic allKeys][indexPath.section] ];
NSDictionary *dic = _sortedAnnArray[indexPath.section] ;
collectionAnnouncments.delegate = self;
collectionAnnouncments.dataSource = self;
// cellHead.text =#"Announcements";
//cellTitle.text = dic[#"anc_title"];
if ([dic[#"announcement_images"] count] > 0)
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ANNOUNCMENT_IMAGES_URL,dic[#"announcement_images"][0][#"wi_image"] ] ]] ;
}
else if([collectionView isEqual:collectionNews]) {
//cellHead.text =#"News";
// NSDictionary *mainDic = collectionViewDic[#"news"];
// NSArray *array = mainDic[ [mainDic allKeys][0] ];
NSDictionary *dic = _sortednewsArray[indexPath.section] ;
collectionNews.delegate = self;
collectionNews.dataSource = self;
//cellTitle.text = dic[#"nf_title"];
if ([dic[#"newsfeed_images"] count] > 0)
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",NEWS_IMAGES_URL,dic[#"newsfeed_images"][0][#"wi_image"] ] ]] ;
}
else if([collectionView isEqual:collectionBulletin]) {
// NSDictionary *mainDic = collectionViewDic[#"bulletin"];
// NSArray *array = mainDic[ _sortedbulletinArray[indexPath.section] ];
NSDictionary *dic = _sortedbulletinArray[indexPath.section] ;
collectionBulletin.delegate = self;
collectionBulletin.dataSource = self;
// cellTitle.text = dic[#"wb_title"];
if ([dic[#"bulletin_images"] count] > 0)
if ([dic[#"bulletin_images"][0][#"wi_type"] isEqualToString:#"video"]) {
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BULLETIN_IMAGES_URL,dic[#"ws_thumb"] ] ]] ;
}
else{
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BULLETIN_IMAGES_URL,dic[#"bulletin_images"][0][#"wi_image"] ] ]] ;
}
}
return cell;
}
#pragma mark UITableView Delegate, DataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 195.0f;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[collectionViewDic allKeys] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"tableCell"];
cell.tag = indexPath.row;
UICollectionView *c = [cell.contentView viewWithTag:111];
//c.scrollEnabled = NO;
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
flow.minimumLineSpacing = flow.minimumInteritemSpacing = 0.0f;
flow.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/1, c.bounds.size.height);
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
// c.collectionViewLayout = flow;
UIView *header = [cell.contentView viewWithTag:1];
UIImageView *headerImage = [header viewWithTag:2];
UILabel *headerTitle = [header viewWithTag:3];
//NSLog(cell.tag);
switch (indexPath.row) {
case 0:
//NSLog(#"text");
headerImage.image = [UIImage imageNamed:#"Announcemets"];
//headerTitle.text = #"Announcments";
headerTitle.text=[Utilities getLocalizedStringForKey:#"Announcement"];
// NSLog(headerTitle.text);
collectionAnnouncments = c;
[collectionAnnouncments setCollectionViewLayout:flow];
collectionAnnouncments.delegate = self;
collectionAnnouncments.dataSource = self;
[collectionAnnouncments reloadData];
// NSLog(#"text");
break;
case 1:
headerImage.image = [UIImage imageNamed:#"News"];
headerTitle.text=[Utilities getLocalizedStringForKey:#"Business Highlight"];
collectionNews = c;
[collectionNews setCollectionViewLayout:flow];
collectionNews.delegate = self;
collectionNews.dataSource = self;
[collectionNews reloadData];
//NSLog(#"text");
break;
case 2:
headerImage.image = [UIImage imageNamed:#"Bulletin"];
headerTitle.text=[Utilities getLocalizedStringForKey:#"Bulletin Board"];
collectionBulletin = c;
[collectionBulletin setCollectionViewLayout:flow];
collectionBulletin.delegate = self;
collectionBulletin.dataSource = self;
[collectionBulletin reloadData];
//NSLog(#"text");
break;
default:
break;
}
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.destinationViewController isKindOfClass:[NewsListing class]]) {
NewsListing *c = segue.destinationViewController;
NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;
if (row == 0) {
c.isAnnouncement = YES;
c.listingArray = collectionViewDic[#"announcement"];
}
else if (row == 1) {
c.isNews = YES;
c.listingArray = collectionViewDic[#"news"];
}
else if (row == 2) {
c.isBulletin = YES;
c.listingArray = collectionViewDic[#"bulletin"];
}
}
if ([segue.destinationViewController isKindOfClass:[NewsDetail class]]) {
NewsDetail *c = segue.destinationViewController;
UICollectionViewCell *cell = sender;
NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;
if (row == 0) {
c.isAnnouncement = YES;
// NSDictionary *months = collectionViewDic[#"announcement"];
NSIndexPath *indexPath = [collectionAnnouncments indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortedAnnArray;
c.detailDic = month[indexPath.section ];
}
else if (row == 1) {
c.isNews = YES;
// NSDictionary *months = collectionViewDic[#"news"];
NSIndexPath *indexPath = [collectionNews indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortednewsArray;
c.detailDic = month[indexPath.section ];
}
else if (row == 2) {
c.isBulletin = YES;
// NSDictionary *months = collectionViewDic[#"bulletin"];
NSIndexPath *indexPath = [collectionBulletin indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortedbulletinArray;
c.detailDic = month[indexPath.section ];
}
}
}
#end
I am using UISegmentedControl and using UITableView but my query is segment button 1 click and display data for yes and 2 button click and display data from no and adding A to Z section UITableView first button click properly data display and properly tableview section atoz display but 2 button click and app crash `
#import "ZnameViewController.h"
#import "ZpaleoViewController.h"
#import "SWRevealViewController.h"
#interface ZnameViewController ()
#end
#implementation ZnameViewController
#synthesize strname1,sagmentController,objtbl,name;
- (void)viewDidLoad {
[super viewDidLoad];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.slide setTarget: self.revealViewController];
[self.slide setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
databse = [FMDatabase databaseWithPath:appdelegate.appDBPath];
[arrCatname removeAllObjects];
[arrPaleo removeAllObjects];
arrCatname = [[NSMutableArray alloc]init];
arrPaleo = [[NSMutableArray alloc]init];
arrStatus = [[NSMutableArray alloc]init];
arrCat2 = [[NSMutableArray alloc]init];
arrSta2 = [[NSMutableArray alloc]init];
[self segmentSwitch:self];
// Do any additional setup after loading the view.
}
- (IBAction)segmentSwitch:(id)sender {
[databse open];
NSString *selectQuery = [NSString stringWithFormat:#"select * from Food ORDER BY name ASC"];
NSLog(#"%#",selectQuery);
FMResultSet *resultQuary = [databse executeQuery:selectQuery];
while ([resultQuary next]) {
// NSString *z_paleo = [resultQuary stringForColumn:#"status"];
z_paleo = [NSString stringWithFormat:#"%d",[resultQuary intForColumn:#"status"]];
if ([z_paleo isEqualToString:#"1"]) {
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrPaleo addObject:#""];
}
else{
[arrPaleo addObject:z_name];
}
[arrSta2 addObject:z_paleo];
}
else{
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrCatname addObject:#""];
}
else
{
[arrCatname addObject:z_name];
}
[arrCat2 addObject:z_paleo];
}
}
[databse close];
if(sagmentController.selectedSegmentIndex == 0)
{
if ([z_paleo isEqualToString:#"1"]) {
[self getName:arrPaleo];
objtbl.hidden = NO;
}
}
else if (sagmentController.selectedSegmentIndex == 1)
{
if ([z_paleo isEqualToString:#"0"]) {
[self getName:arrCatname];
objtbl.hidden = NO;
}
}
[objtbl reloadData];
}
-(void)getName:(NSMutableArray *)arr
{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < arr.count; i++)
{
NSString *string = [arr objectAtIndex:i];
dict = [[NSMutableDictionary alloc] init];
[dict setObject:string forKey:#"Name"];
[dict setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict];
}
[temp addObject:temp2];
sorted = [[NSArray alloc] initWithArray:temp];
}
-(void)getname2:(NSMutableArray *)array{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *string = [array objectAtIndex:i];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:string forKey:#"Name"];
[dict1 setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict1];
}
[temp addObject:temp2];
sorted1 = [[NSArray alloc] initWithArray:temp];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
int i = 0;
for(NSArray *array in sorted)
{
NSString *string = [array objectAtIndex:0];
if([string compare:title] == NSOrderedSame)
break;
i++;
}
return i;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (sagmentController.selectedSegmentIndex == 0) {
return [sorted count];
}else {
return [sorted count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *array = [sorted objectAtIndex:section];
return [array objectAtIndex:0];
//return [foodIndexTitles objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSMutableArray *titleArray = [NSMutableArray array];
[titleArray addObject:#"A"];
[titleArray addObject:#"B"];
[titleArray addObject:#"C"];
[titleArray addObject:#"D"];
[titleArray addObject:#"E"];
[titleArray addObject:#"F"];
[titleArray addObject:#"G"];
[titleArray addObject:#"H"];
[titleArray addObject:#"I"];
[titleArray addObject:#"J"];
[titleArray addObject:#"K"];
[titleArray addObject:#"L"];
[titleArray addObject:#"M"];
[titleArray addObject:#"N"];
[titleArray addObject:#"O"];
[titleArray addObject:#"P"];
[titleArray addObject:#"Q"];
[titleArray addObject:#"R"];
[titleArray addObject:#"S"];
[titleArray addObject:#"T"];
[titleArray addObject:#"U"];
[titleArray addObject:#"V"];
[titleArray addObject:#"W"];
[titleArray addObject:#"X"];
[titleArray addObject:#"Y"];
[titleArray addObject:#"Z"];
return titleArray;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (sagmentController.selectedSegmentIndex == 1) {
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}else{
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifire = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifire];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifire];
}
if (sagmentController.selectedSegmentIndex == 0) {
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Yes_check.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
}
else
{
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"No.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
return cell;
}
return cell;
}
I am fetching contact from device and show in tableview
but first time on contact screen pop show for contact permission, when i click on okey tableview numberofrow called but cellForRowAtIndexPath calling after 5 seconds
I am using this code (this problem only comes first time when new app install)
and i added delegate and datasource in xib and .h file
-(void)getContactsFromAddressBook
{
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBook,
^(bool granted, CFErrorRef error) {
if (granted)
[self loadContacts];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
[self loadContacts];
}
else {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:Nil message:#"You don't have permission of access contacts for access go to Setting-> Doubls-> Contacts" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
//Load contact
-(void)loadContacts
{
[arr_Contact removeAllObjects];
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
//arr_Contact = (__bridge NSMutableArray*)allPeople;
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
//NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString *phoneNumber;
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
// NSLog(#"phone:%#", phoneNumber);
}
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
if(firstName == nil)
{
firstName = #"";
}
if(lastName == nil)
{
lastName = #"";
}
if(phoneNumber == nil)
{
continue;
}
[dic setValue:[NSString stringWithFormat:#"%# %#",firstName,lastName] forKey:#"firstName"];
//[dic setValue:lastName forKey:#"lastName"];
[dic setValue:phoneNumber forKey:#"phonesNum"];
[arr_Contact addObject:dic];
}
NSLog(#"arr all contact %#",arr_Contact);
NSSortDescriptor *sorter = [[NSSortDescriptor alloc]
initWithKey:#"firstName"
ascending:YES
selector:#selector(compare:)] ;
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[arr_Contact sortUsingDescriptors:sortDescriptors];
[arr_afterSearch addObjectsFromArray:arr_Contact];
[self createSectionList:arr_Contact];
}
//create section
- (void) createSectionList: (id) wordArray
{
for (int i = 0; i < 27; i++) [arr_searchContact addObject:[[NSMutableArray alloc] init]];
int k=0;
NSLog(#"arr count is %lu",(unsigned long)[arr_Contact count]);
for (k=0; k<[arr_Contact count]; k++) {
NSString *word = [NSString stringWithFormat:#"%#",[[arr_Contact valueForKey:#"firstName"]objectAtIndex:k]];
if ([word length] == 0) continue;
#try {
range1 = [ALPHA rangeOfString:[[word substringToIndex:1] uppercaseString]];
[[arr_searchContact objectAtIndex:range1.location]addObject:[arr_Contact objectAtIndex:k]];
}
#catch (NSException * e) {
[[arr_searchContact objectAtIndex:26]addObject:[arr_Contact objectAtIndex:k]];
NSLog(#"error");
}
#finally {
}
}
[self.tblContact reloadData];
}
//tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows=0;
if (IsSearching==TRUE) {
rows=[arr_afterSearch count];
}
else{
rows=[[arr_searchContact objectAtIndex:section] count];
}
return rows;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger section=0;
if (IsSearching==TRUE) {
section=1;
}
else{
if ([arr_searchContact count]>0) {
section=[ALPHA_ARRAY count];
}
else{
section=0;
}
}
return section;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
if (IsSearching==TRUE) {
return nil;
}
else{
return ALPHA_ARRAY;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
// create the parent view that will hold header Label
if (IsSearching==TRUE) {
return nil;
}
else{
if([[arr_searchContact objectAtIndex:section] count]==0)
{
return nil;
}
else {
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(5.0, 0.0, 320.0, 25.0)];
[customView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:239.0/255.0 blue:240.0/255.0 alpha:1.0]];
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.font = [UIFont systemFontOfSize:14];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 24.0);
[headerLabel setText:[NSString stringWithFormat:#"%#",[ALPHA_ARRAY objectAtIndex:section]]];
[headerLabel setTextColor:[UIColor lightGrayColor]];
[customView addSubview:headerLabel];
return customView;
}
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (IsSearching==TRUE) {
return 0;
}
else{
if([[arr_searchContact objectAtIndex:section] count]==0)
{
return 0;
}
else
{
return 25;
}
}
}
-(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];
cell.backgroundColor=[UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
UIView *selectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 280, 46)];
[selectionView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:82.0/255.0 blue:91.0/255.0 alpha:1.0]];
cell.selectedBackgroundView = selectionView;
if ([tableView respondsToSelector:#selector(setSectionIndexColor:)]) {
tableView.sectionIndexBackgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:0.3];
tableView.sectionIndexTrackingBackgroundColor = [UIColor whiteColor];
}
}
NSMutableDictionary *dic = [arr_Contact objectAtIndex:indexPath.row];
//cell.textLabel.text = [dic objectForKey:#"firstName"];
//cell.lastNameLabel.text = [dic objectForKey:#"lastName"];
if (IsSearching==TRUE) {
NSDictionary *dic=[arr_afterSearch objectAtIndex:indexPath.row];
if ([[dic objectForKey:#"firstName"] length]>0) {
cell.textLabel.text = [dic objectForKey:#"firstName"];
}
else{
cell.textLabel.text =[dic objectForKey:#"phonesNum"];
}
}
else{
NSDictionary *dic=[[arr_searchContact objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
if ([[dic objectForKey:#"firstName"] length]>0) {
cell.textLabel.text = [dic objectForKey:#"firstName"];
}
else{
cell.textLabel.text =[dic objectForKey:#"phonesNum"];
}
}
cell.textLabel.textColor=[UIColor darkGrayColor];
cell.textLabel.highlightedTextColor = [UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:#"OpenSans" size:14.0];
return cell;
}
You need to ensure that you only update the UI from the main queue. Your completion handler for the address book access will be executing on a background thread. Change the completion handler to invoke loadContacts on the main queue.
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBook,
^(bool granted, CFErrorRef error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[self loadContacts];
});
}
});
i'm using UiScrollSlidingPages (https://github.com/TomThorpe/UIScrollSlidingPages) plugin but i have a problem. The displayed view for every page is the same and it is the last one view allocated.
This is the method of datasource delegate that i'm using
-(TTSlidingPage *)pageForSlidingPagesViewController:(TTScrollSlidingPagesController*)source atIndex:(int)index{
variabiliGlobali.paginaFormazione = index + 1;
UIViewController *viewController;
viewController = [[foaPaginaFormazioneVC alloc] init];
return [[TTSlidingPage alloc] initWithContentViewController:viewController];
}
This is the foaPaginaFormazioneVC code.
#import "foaPaginaFormazioneVC.h"
#import "foaAppDelegate.h"
#import "foaVotoCalciatoreCell.h"
#import "foaBonusTotaliCell.h"
#import "foaRiepilogoCell.h"
#implementation foaPaginaFormazioneVC
foaAppDelegate *variabiliGlobali;
NSDictionary *formazione;
NSDictionary *elencoCalciatori;
NSDictionary *logFormazione;
NSDictionary *logCalcolo;
NSMutableArray *titolari;
NSMutableArray *panchinari;
NSMutableArray *logForTipo;
NSMutableArray *logForValore;
NSMutableArray *logCalTipo;
NSMutableArray *logCalValore;
bool calcolata;
- (void)viewDidLoad
{
[super viewDidLoad];
self.cellZoomInitialAlpha = [NSNumber numberWithFloat:1.0];
self.cellZoomAnimationDuration = [NSNumber numberWithFloat:0.5];
self.cellZoomXScaleFactor = [NSNumber numberWithFloat:0.9];
self.cellZoomYScaleFactor = [NSNumber numberWithFloat:0.9];
variabiliGlobali = (foaAppDelegate *)[[UIApplication sharedApplication] delegate];
formazione = [variabiliGlobali.formazioniA objectAtIndex: variabiliGlobali.paginaFormazione - 1];
elencoCalciatori = [[NSDictionary alloc] init];
logFormazione = [[NSDictionary alloc] init];
logCalcolo = [[NSDictionary alloc] init];
if ([formazione objectForKey:#"FORMAZIONE"] != [NSNull null]) {
elencoCalciatori = [formazione objectForKey:#"FORMAZIONE"];
}
if ([formazione objectForKey:#"LOG_FORMAZIONE"] != [NSNull null]) {
logFormazione = [formazione objectForKey:#"LOG_FORMAZIONE"];
}
if ([formazione objectForKey:#"LOG_CALCOLO"] != [NSNull null]) {
logCalcolo = [formazione objectForKey:#"LOG_CALCOLO"];
}
titolari = [[NSMutableArray alloc] init];
panchinari = [[NSMutableArray alloc] init];
for (NSDictionary *dict in elencoCalciatori) {
if ([[dict objectForKey:#"ORDINE"] intValue] <= 11) {
[titolari addObject: dict];
}
else {
[panchinari addObject: dict];
}
}
logForTipo = [[NSMutableArray alloc] init];
logForValore = [[NSMutableArray alloc] init];
logCalTipo = [[NSMutableArray alloc] init];
logCalValore = [[NSMutableArray alloc] init];
NSString *appString;
bool appBool;
float appNumber;
if ([logFormazione count] != 0) {
//AMMINISTRATORE
appBool = [[logFormazione objectForKey:#"AMMINISTRATORE"] boolValue];
if (appBool) {
[logForTipo addObject: #"Formazione inserita dall'amministratore"];
[logForValore addObject: #""];
}
//MODULO INIZIALE
appString = [logFormazione objectForKey:#"MODULO_INIZIALE"];
[logForTipo addObject: #"Modulo Iniziale"];
[logForValore addObject: appString];
//DATA
appString = [logFormazione objectForKey:#"DATA"];
[logForTipo addObject: #"Data Ultima Modifica"];
[logForValore addObject: appString];
}
if ([logCalcolo count] != 0) {
//MODULO FINALE
appString = [logCalcolo objectForKey:#"MODULO_FINALE"];
[logForTipo addObject: #"Modulo Finale"];
[logForValore addObject: appString];
//PORTIERE IMBATTUTO
appNumber = [[logCalcolo objectForKey:#"PORTIERE_IMBATTUTO"] doubleValue];
if (appNumber != 0) {
NSNumber *doubleNumber = [NSNumber numberWithDouble:appNumber];
[logCalTipo addObject: #"Portiere Imbattuto"];
[logCalValore addObject: [doubleNumber stringValue]];
}
//MOD_P
appNumber = [[logCalcolo objectForKey:#"MOD_P"] doubleValue];
if (appNumber != 0) {
NSNumber *doubleNumber = [NSNumber numberWithDouble:appNumber];
[logCalTipo addObject: #"Modificatore Portiere"];
[logCalValore addObject: [doubleNumber stringValue]];
}
//MOD_D
appNumber = [[logCalcolo objectForKey:#"MOD_D"] doubleValue];
if (appNumber != 0) {
NSNumber *doubleNumber = [NSNumber numberWithDouble:appNumber];
[logCalTipo addObject: #"Modificatore Difesa"];
[logCalValore addObject: [doubleNumber stringValue]];
}
//MOD_C
appNumber = [[logCalcolo objectForKey:#"MOD_C"] doubleValue];
if (appNumber != 0) {
NSNumber *doubleNumber = [NSNumber numberWithDouble:appNumber];
[logCalTipo addObject: #"Modificatore Centrocampo"];
[logCalValore addObject: [doubleNumber stringValue]];
}
//MOD_A
appNumber = [[logCalcolo objectForKey:#"MOD_A"] doubleValue];
if (appNumber != 0) {
NSNumber *doubleNumber = [NSNumber numberWithDouble:appNumber];
[logCalTipo addObject: #"Modificatore Attacco"];
[logCalValore addObject: [doubleNumber stringValue]];
}
//PUNTEGGIO
appNumber = [[logCalcolo objectForKey:#"PUNTEGGIO"] doubleValue];
if (appNumber != 0) {
NSNumber *doubleNumber = [NSNumber numberWithDouble:appNumber];
[logCalTipo addObject: #"Punteggio Finale"];
[logCalValore addObject: [doubleNumber stringValue]];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (variabiliGlobali.gioCalcolata) {
return 4;
}
else {
return 3;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger *numero;
//La giornata è calcolata. Sezione 2 = BONUS e TOTALI
if (variabiliGlobali.gioCalcolata && section == 2) {
numero = [logCalTipo count];
}
//La giornata è calcolata. Sezione 3 = RIEPILOGO
//La giornata non è calcolata. Sezione 2 = RIEPILOGO
if ((variabiliGlobali.gioCalcolata && section == 3) || (variabiliGlobali.gioCalcolata == false && section == 2)) {
numero = [logForTipo count];
}
if (section == 1)
{numero = [panchinari count];}
if ( section == 0)
{numero = [titolari count];}
return numero;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *idDettCal = #"cellaVotoCalciatore";
NSString *idRiepilogo = #"riepilogoCell";
NSString *idTotali = #"bonusTotaliCell";
//Dictionary per Titolari e Panchinari
NSDictionary *calciatore;
if (indexPath.section == 0 || indexPath.section == 1) {
foaVotoCalciatoreCell *cell = (foaVotoCalciatoreCell *)[tableView dequeueReusableCellWithIdentifier:idDettCal];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idDettCal owner:self options:nil];
cell = [nib objectAtIndex:0];
}
//TITOLARI
if (indexPath.section == 0) {
calciatore = [titolari objectAtIndex:indexPath.row];
}
//PANCHINARI
else if (indexPath.section == 1) {
calciatore = [panchinari objectAtIndex:indexPath.row];
}
NSString *calciatoreStr =
[NSString stringWithFormat:#"%#%#%#%#",
[calciatore objectForKey:#"CALCIATORE"],
#" (",
[[calciatore objectForKey:#"SQUADRA"] substringToIndex:3],
#")"];
NSString *imgRuolo =
[NSString stringWithFormat:#"%#%#",
[calciatore objectForKey:#"RUOLO"],
#".jpg"];
cell.ruolo.image = [UIImage imageNamed:imgRuolo];
NSDictionary *dettaglioVoto;
UIImageView *imageIcona;
CGFloat offset;
dettaglioVoto = [calciatore objectForKey:#"VOTO_STM"];
offset = 0;
for (NSString *icona in dettaglioVoto) {
if ([icona isEqualToString: #"AMMONITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"amm.png"]];
}
else if ([icona isEqualToString: #"GOL_FATTO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golfatto.png"]];
}
else if ([icona isEqualToString: #"GOL_SUBITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golsubito.png"]];
}
else if ([icona isEqualToString: #"ENTRATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"entrato.png"]];
}
else if ([icona isEqualToString: #"USCITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"uscito.png"]];
}
else if ([icona isEqualToString: #"ESPULSO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"esp.png"]];
}
else if ([icona isEqualToString: #"ASSIST"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"assist.png"]];
}
else if ([icona isEqualToString: #"ASSIST_FERMO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"assistf.png"]];
}
else if ([icona isEqualToString: #"RIGORE_SEGNATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoresegnato.png"]];
}
else if ([icona isEqualToString: #"RIGORE_SBAGLIATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoresbagliato.png"]];
}
else if ([icona isEqualToString: #"RIGORE_PARATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoreparato.png"]];
}
else if ([icona isEqualToString: #"AUTOGOL"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"autogol.png"]];
}
else if ([icona isEqualToString: #"GOL_PARTITA"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golvittoria.png"]];
}
else if ([icona isEqualToString: #"GOL_PAREGGIO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golpareggio.png"]];
}
imageIcona.frame = CGRectMake(offset, 0, imageIcona.frame.size.width, imageIcona.frame.size.height);
//imageIcona.frame = CGRectMake(offset, 0, 20, 20);
offset = imageIcona.frame.size.width + offset + 2;
[cell.iconeDettaglio addSubview: imageIcona];
}
if (offset == 0) {
//cell.calciatore.frame = CGRectMake(cell.calciatore.frame.origin.x, 14, cell.calciatore.frame.size.width, cell.calciatore.frame.size.height);
}
cell.calciatore.text = calciatoreStr;
cell.votoIniziale.text = [calciatore objectForKey:#"VOTO_PRNT"];
cell.votoFinale.text = [calciatore objectForKey:#"VOTO_PRNT_TOT"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
//La giornata è calcolata. Sezione 2 = BONUS e TOTALI
else if (variabiliGlobali.gioCalcolata && indexPath.section == 2) {
NSDictionary *totaliVal;
NSDictionary *totaliTip;
totaliVal = [logCalValore objectAtIndex:indexPath.row];
totaliTip = [logCalTipo objectAtIndex:indexPath.row];
foaBonusTotaliCell *cell = (foaBonusTotaliCell *)[tableView dequeueReusableCellWithIdentifier:idTotali];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idTotali owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.tipoBonusLabel.text = totaliTip;
cell.totaleLabel.text = totaliVal;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
//La giornata è calcolata. Sezione 3 = RIEPILOGO
//La giornata non è calcolata. Sezione 2 = RIEPILOGO
//else ((variabiliGlobali.gioCalcolata && indexPath.section == 3) ||
// (variabiliGlobali.gioCalcolata == false && indexPath.section == 2)) {
//}
else {
NSDictionary *riepilogoVal;
NSDictionary *riepilogoTip;
riepilogoVal = [logForValore objectAtIndex:indexPath.row];
riepilogoTip = [logForTipo objectAtIndex:indexPath.row];
foaRiepilogoCell *cell = (foaRiepilogoCell *)[tableView dequeueReusableCellWithIdentifier:idRiepilogo];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idRiepilogo owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.voceRiepilogoLabel.text = riepilogoTip;
cell.valoreRiepilogoLabel.text = riepilogoVal;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString *header;
if (variabiliGlobali.gioCalcolata && section == 2) {
header = #"Bonus e Totale";
}
if ((variabiliGlobali.gioCalcolata && section == 3) || (variabiliGlobali.gioCalcolata == false && section == 2)) {
header = #"Riepilogo";
}
if (section == 1)
{header = #"Panchinari";}
if ( section == 0)
{header = #"Titolari";}
return header;
}
#end
If i use another simple view (with only one random label) the plugin works fine.
What is the matter?
Thanks in advance.
I have resolved my question declaring these variable
NSDictionary *formazione;
NSDictionary *elencoCalciatori;
NSDictionary *logFormazione;
NSDictionary *logCalcolo;
NSMutableArray *titolari;
NSMutableArray *panchinari;
NSMutableArray *logForTipo;
NSMutableArray *logForValore;
NSMutableArray *logCalTipo;
NSMutableArray *logCalValore;
bool calcolata;
in .h files of ViewController.
I need to filter data in UITableview by text entered in UISearchbar. I followed this example but there data in NSMutableArray and I can't alter it under my requirements. My data is NSMutableDictionary. I'm stuck on this for long time.
My data:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:#"data.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSDictionary *myDict = [NSDictionary dictionaryWithContentsOfFile:path];
sectionKeys = [NSMutableArray new];
sectionsTitle = [NSMutableArray new];
NSArray *tableArray = [myDict objectForKey:#"Black"];
[resultArray addObject:#"Black"];
[resultDic setValue:tableArray forKey:#"Black"];
[sectionsTitle addObject:[NSString stringWithFormat:#"%#", [tableData valueForKey:#"Black"]]];
[sectionCord addObject:[NSString stringWithFormat:#"%#", [tableData valueForKey:#"Coordinates"]]];
[sectionKeys addObject:#"Section1"];
self.tableData = resultDic;
self.sectionsTitle = resultArray;
[myTable reloadData];
My table:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionKeys.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionKeys objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int rowCount;
if(self.isFiltered)
rowCount = [[filteredTableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
else
rowCount = [[tableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
if(isFiltered){
NSDictionary *dict = [[filteredTableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Address"]];
}
else{
NSDictionary *dict = [[tableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Address"]];
}
return cell;
}
My search:
#pragma mark - SearchBar Delegate -
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text{
if(text.length == 0)
{
isFiltered = FALSE;
NSLog(#"false");
}
else
{
isFiltered = true;
NSLog(#"true");
filteredTableData = [[NSMutableDictionary alloc] init];
for (MyAnnotation* ann in tableData)
{
NSRange nameRange = [ann.title rangeOfString:text options:NSCaseInsensitiveSearch];
NSRange descriptionRange = [ann.description rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:ann];
//error
}
}
}
[myTable reloadData];
}
First of all, you need to create a state/flag for the controller/data source, in order for it to know weather you are in search/filter mode.
Then, if you are in search mode, point the data source methods to the filteredArray.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
int numberOfSections = 0;
if (_searchMode)
{
numberOfSections = self.filteredDataDict.allKeys.count;
}
else
{
numberOfSections = self.tableData.allKeys.count;
}
return numberOfSections;
}
Hope it's understood.