Dynamic expandable and collapsed table view cells? - ios

I developed expandable and collapsed table view for dynamic data comes from the server. I'm displaying state names in header view successfully, but I can't displaying child data that is districts related to state names.
I followed Link for this http://www.iostute.com/2015/04/expandable-and-collapsable-tableview.html
My data is
_response = #{#"Response":#{#"status":#"SUCCESS",#"error_code":#"0",#"message":#"SUCCESS",#"Array":#[
#{#"state_id":#"0",#"state_name":#"null",#"district_id":#"0",#"district_name":#"null"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"001",#"district_name":#"State1District1"},
#{#"state_id":#"02",#"state_name":#"State2",#"district_id":#"004",#"district_name":#"State2District1"},
#{#"state_id":#"02",#"state_name":#"State2",#"district_id":#"005",#"district_name":#"State3District1"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"002",#"district_name":#"State1District2"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"003",#"district_name":#"State1District3"},
#{#"state_id":#"03",#"state_name":#"State3",#"district_id":#"006",#"district_name":#"State3District1"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"008",#"district_name":#"State4District1"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"009",#"district_name":#"State4District2"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"010",#"district_name":#"State4District3"},
#{#"state_id":#"05",#"state_name":#"State5",#"district_id":#"011",#"district_name":#"State5District1"},
#{#"state_id":#"05",#"state_name":#"State5",#"district_id":#"012",#"district_name":#"State5District2"},
#{#"state_id":#"03",#"state_name":#"State3",#"district_id":#"007",#"district_name":#"State3District2"}]}, #"count":#"6"};
My code is
if ([[[_response objectForKey:#"Response"] objectForKey:#"status"] isEqualToString:#"SUCCESS"] && (!(_integer == 0))) {
_stateID = [[NSMutableArray alloc] init];
_stateName = [[NSMutableArray alloc] init];
_districtID = [[NSMutableArray alloc] init];
_districtName = [[NSMutableArray alloc] init];
_stateIdStateNameDic = [[NSMutableDictionary alloc]init];
//Add arrays to array to remove null values dynamically
NSArray *arr = [[NSArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil];
for (int i=0; i<_integer; i++) {
[_stateID addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_id"]];
[_stateName addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_name"]];
[_districtID addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_id"]];
[_districtName addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"]];
//Remove null values
for (int j=0; j<arr.count; j++) {
for (NSMutableArray *ar in arr) {
if ([[ar objectAtIndex:i] isKindOfClass:[NSNull class]] || [[ar objectAtIndex:i] isEqualToString:#"null"] || [[ar objectAtIndex:i] isEqualToString:#"0"]) {
[ar addObject:#""];
[ar removeObjectAtIndex:i];
}
}
}
}
//Add arrays to mutable array to remove empty objects
NSMutableArray *marr = [[NSMutableArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil];
//Remove empty objects from all arrays
for (int j=0; j<marr.count; j++) {
for (int i=0; i<[[marr objectAtIndex:j] count]; i++) {
if ([[[marr objectAtIndex:j] objectAtIndex:i] isEqualToString:#""]) {
[[marr objectAtIndex:j] removeObjectAtIndex:i];
}
}
}
//Remove duplicates from state names array
_stateName = [_stateName valueForKeyPath:#"#distinctUnionOfObjects.self"];
NSString *districtName = #"";
NSString * superater = #"&&";
_mdic = [[NSMutableDictionary alloc]init];
for (int j=0; j<_stateName.count; j++) {
for (int i=0; i<_integer; i++) {
if ([[_stateName objectAtIndex:j] isEqualToString:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_name"]]) {
//Remove district name if empty or null
if ([districtName isEqualToString:#""] || [districtName isEqual:[NSNull null]]) {
districtName = [[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"];
if ([districtName isEqual:[NSNull null]] || [districtName isEqualToString:#"null"]) {
districtName = #"";
}
} else {
//Add all districts with superater &&
districtName = [districtName stringByAppendingString:[NSString stringWithFormat:#"%#%#", superater, [[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"]]];
}
}
}
//Create district names dictionary with state name keys
[_mdic setValue:districtName forKey:[_stateName objectAtIndex:j]];
districtName = #"";
}
NSLog(#"_mdic %#", _mdic);
_arrayForBool=[[NSMutableArray alloc]init];
//Save bool value " NO " based on sectionTitleArray count.
for (int i=0; i<[_stateName count]; i++) {
[_arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[_availableOrdersTableView reloadData];
});
} else {
}
// TableView delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [_mdic count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Number of rows in each section
if ([[_arrayForBool objectAtIndex:section] boolValue]) {
NSLog(#"%#", [_stateName objectAtIndex:section]);
NSLog(#"%#", _mdic);
NSArray *mdicKeys = [_mdic allKeys];
for (int i=0; i<_mdic.count; i++) {
if ([[mdicKeys objectAtIndex:i] isEqualToString:[_stateName objectAtIndex:section]]) {
NSString *str = [_mdic objectForKey:[_stateName objectAtIndex:section]];
NSLog(#"%#", str);
_subDistrictArr = [str componentsSeparatedByString:#"&&"];
}
}
NSLog(#"_subDistrictIDArr %#", _subDistrictArr);
return _subDistrictArr.count;
} else {
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Create cell
static NSString *cellid=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
}
BOOL manyCells = [[_arrayForBool objectAtIndex:indexPath.section] boolValue];
/********** If the section supposed to be closed *******************/
if(!manyCells)
{
cell.backgroundColor=[UIColor clearColor];
cell.textLabel.text=#"";
}
/********** If the section supposed to be Opened *******************/
else {
cell.textLabel.text=[_subDistrictArr objectAtIndex:indexPath.row];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
cell.textLabel.font=[UIFont systemFontOfSize:20.0f];
} else {
cell.textLabel.font=[UIFont systemFontOfSize:15.0f];
}
cell.backgroundColor=[UIColor whiteColor];
cell.selectionStyle=UITableViewCellSelectionStyleNone ;
}
cell.textLabel.textColor=[UIColor blackColor];
/********** Add a custom Separator with cell *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(15, 48, _availableOrdersTableView.frame.size.width-15, 1)];
separatorLineView.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:separatorLineView];
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *sectionView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, 50)];
sectionView.backgroundColor = [UIColor clearColor];
sectionView.tag=section;
UILabel *viewLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, sectionView.frame.size.height)];
viewLabel.backgroundColor=[UIColor clearColor];
viewLabel.textColor=[UIColor blackColor];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
viewLabel.font=[UIFont systemFontOfSize:25];
} else {
viewLabel.font=[UIFont systemFontOfSize:15];
}
viewLabel.text=[NSString stringWithFormat:#"%#", [_stateName objectAtIndex:section]];
_stateIDString = [_stateID objectAtIndex:section];
NSLog(#"stateIDString %#", _stateIDString);
[sectionView addSubview:viewLabel];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-45, (sectionView.frame.size.height-25)/2, 18, 17)];
imgView.tag = section;
imgView.image = [UIImage imageNamed:#"DA"];
[sectionView addSubview:imgView];
} else {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-35, (sectionView.frame.size.height-25)/2, 18, 17)];
imgView.tag = section;
imgView.image = [UIImage imageNamed:#"DA"];
[sectionView addSubview:imgView];
}
/********** Add a custom Separator with Section view *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.frame.size.height, _availableOrdersTableView.frame.size.width, 1)];
separatorLineView.backgroundColor = [UIColor blackColor];
[sectionView addSubview:separatorLineView];
/********** Add UITapGestureRecognizer to SectionView **************/
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionView addGestureRecognizer:headerTapped];
return sectionView;
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
// _gestureInteger = gestureRecognizer.view.tag;
if (indexPath.row == 0) {
BOOL collapsed = [[_arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[_stateName count]; i++) {
if (indexPath.section==i) {
[_arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}
}
[_availableOrdersTableView reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
// [_availableOrdersTableView reloadData];
}
}

I have two solution for this
(1) initially you put numberofrow for any section is zero and after click on any section you can add row for for clicked section.
(2) number of section will be one and you need to use two cell "cellwithheaderonly" and "cellwithheaderandsubpart" initially you will use "cellwithheaderonly" and when user will click on any cell you need to use "cellwithheaderandsubpart"
You can take reference from following URL
Expanding and Collapsing table view cells in ios
https://www.anexinet.com/blog/expandable-collapsible-uitableview-sections/

You have to maintain an array given below : -
lat arr = [[“name”:”firstRow” , “subRowArray”:[1,2,3,4]],[“name”:”secondRow” , “subRowArray”:[1,2,3,4]],[“name”:”thirdRow” , “subRowArray”:[1,2,3,4]]]
then expand and collapse according to your array .
if would you like to use library then go for expendable Tableview

Related

How to apply multiple arrays in expandable tableview in ios

Hi i have tried to apply multiple arrays in expandable tableview.
but when i run my code it's showing exception.
exception:'Invalid update: invalid number of rows in section 1. The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)
how to solve this exception (or) any other example is available please suggest me.
please help me.
My Code:
.m file
#import "ExpandableListviewWithServices.h"
#interface ExpandableListviewWithServices (){
BackGroundPostServiceClass3 * back;
NSMutableArray *arrayForBool,*totalListOfArray,*respArray;
NSArray *sectionTitleArray;
UITableView *tableList;
}
#end
#implementation ExpandableListviewWithServices
- (void)viewDidLoad {
[super viewDidLoad];
tableList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
tableList.translatesAutoresizingMaskIntoConstraints = NO;
tableList.dataSource=self;
tableList.delegate=self;
tableList.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
tableList.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
tableList.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
[tableList registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
tableList.estimatedRowHeight = 44.0;
tableList.rowHeight = UITableViewAutomaticDimension;
[self.view addSubview:tableList];
NSDictionary * views = NSDictionaryOfVariableBindings(tableList);
NSArray * horizentalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[tableList]-0-|" options:0 metrics:nil views:views];
NSArray * verticalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[tableList]-0-|"options:0 metrics:nil views:views];
[self.view addConstraints:horizentalConstraint];
[self.view addConstraints:verticalConstraint];
[self initialization];
}
-(void)initialization
{
arrayForBool=[[NSMutableArray alloc]init];
sectionTitleArray=[[NSArray alloc]initWithObjects:
#"Apple",
#"Strawberry",
#"Grapes",
#"Orange",
#"Banana",
nil];
NSArray *new0=[[NSArray alloc]initWithObjects:#"Apple", #"Strawberry",#"Grapes",#"Orange", nil];
NSArray *new1=[[NSArray alloc]initWithObjects:#"Apple1", #"Strawberry1",#"Grapes1",#"Orange1"#"Orange1", nil];
NSArray *new2=[[NSArray alloc]initWithObjects:#"Apple2", #"Strawberry2",#"Grapes2",#"Orange2", nil];
NSArray *new3=[[NSArray alloc]initWithObjects:#"Apple3", #"Strawberry3",#"Grapes3",#"Orange3",#"Orange3", nil];
NSArray *new4=[[NSArray alloc]initWithObjects:#"Apple4", #"Strawberry4",#"Grapes4",#"Grapes4", nil];
totalListOfArray=[[NSMutableArray alloc]init];
[totalListOfArray addObject:new0];
[totalListOfArray addObject:new1];
[totalListOfArray addObject:new2];
[totalListOfArray addObject:new3];
[totalListOfArray addObject:new4];
for (int i=0; i<[sectionTitleArray count]; i++) {
[arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[arrayForBool objectAtIndex:section] boolValue]) {
return [respArray count];
}
else
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell2";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
BOOL manyCells = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
// /********** If the section supposed to be closed *******************/
if(!manyCells)
{
cell.backgroundColor=[UIColor clearColor];
cell.textLabel.text=#"";
}
/********** If the section supposed to be Opened *******************/
else
{
cell.textLabel.text=[NSString stringWithFormat:#"%#",[respArray objectAtIndex:indexPath.row]];
cell.textLabel.font=[UIFont systemFontOfSize:15.0f];
cell.backgroundColor=[UIColor whiteColor];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
cell.textLabel.textColor=[UIColor blackColor];
/********** Add a custom Separator with cell *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, tableList.frame.size.width, 1)];
separatorLineView.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:separatorLineView];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [sectionTitleArray count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
/*************** Close the section, once the data is selected ***********************************/
[arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
[tableList reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[arrayForBool objectAtIndex:indexPath.section] boolValue]) {
return 40;
}
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 15;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *sectionView1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,40)];
sectionView1.backgroundColor = [UIColor whiteColor];
return sectionView1;
}
#pragma mark - Creating View for TableView Section
//# #e0e0eb place this color
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerview = [[UIView alloc] init];
headerview.backgroundColor = [UIColor lightGrayColor];
headerview.frame = CGRectMake(0, 0, tableView.frame.size.width, 80);
headerview.tag=section;
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, tableList.frame.size.width, 25)];
label1.text = #"Hi";
[headerview addSubview:label1];
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[headerview addGestureRecognizer:headerTapped];
return headerview;
}
#pragma mark - Table header gesture tapped
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
NSLog(#" index ---->>> %ld",(long)indexPath.section);
for (int i=0; i<[sectionTitleArray count]; i++){
if (indexPath.section == i) {
BOOL collapsed = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[sectionTitleArray count]; i++) {
if (indexPath.section==i) {
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}else{
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:collapsed]];
}
}
[self selectedOption:(int)indexPath.section];
[tableList reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
}
-(NSMutableArray *)selectedOption:(int)mySelectedItemData{
NSLog(#"%d",mySelectedItemData);
NSMutableArray *arrayValue=[[NSMutableArray alloc]init];
respArray=[[NSMutableArray alloc]init];
NSLog(#"%#",[totalListOfArray objectAtIndex:mySelectedItemData]);
NSLog(#"%d",[[totalListOfArray objectAtIndex:mySelectedItemData] count]);
for (int i=0; i< [[totalListOfArray objectAtIndex:mySelectedItemData]count]; i++) {
[arrayValue addObject:[[totalListOfArray objectAtIndex:mySelectedItemData] objectAtIndex:i]];
//[arrayValue addObject:[itemsArray objectAtIndex:mySelectedItemData]];
NSLog(#"array value is =======> %#",arrayValue);
[arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
respArray=[arrayValue mutableCopy];
NSLog(#"respArray items are =====> %#",respArray);
return arrayValue;
}
I am placing the below functions with code change which you have done. See, understand and replace the function with your code.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *arrayCount = [totalListOfArray objectAtIndex:section];
return [arrayCount count];
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
NSLog(#" index ---->>> %ld",(long)indexPath.section);
for (int i=0; i<[sectionTitleArray count]; i++){
if (indexPath.section == i) {
BOOL collapsed = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[sectionTitleArray count]; i++) {
if (indexPath.section==i) {
if (collapsed == NO) {
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:YES]];
}
else{
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
}else{
NSLog(#"%#",arrayForBool);
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
}
[self selectedOption:(int)indexPath.section];
}
}
}
-(NSMutableArray *)selectedOption:(int)mySelectedItemData{
NSLog(#"%d",mySelectedItemData);
NSMutableArray *arrayValue=[[NSMutableArray alloc]init];
respArray=[[NSMutableArray alloc]init];
NSLog(#"%#",[totalListOfArray objectAtIndex:mySelectedItemData]);
NSLog(#"%lu",(unsigned long)[[totalListOfArray objectAtIndex:mySelectedItemData] count]);
for (int i=0; i< [[totalListOfArray objectAtIndex:mySelectedItemData]count]; i++) {
[arrayValue addObject:[[totalListOfArray objectAtIndex:mySelectedItemData] objectAtIndex:i]];
NSLog(#"array value is =======> %#",arrayValue);
}
respArray=[arrayValue mutableCopy];
[tableList reloadSections:[NSIndexSet indexSetWithIndex:mySelectedItemData] withRowAnimation:UITableViewRowAnimationAutomatic];
NSLog(#"respArray items are =====> %#",respArray);
return arrayValue;
}

UISegmentedControl in iOS

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;
}

ios: NSMutableArray Count Prints Zero after adding object?

My project is based on parsing xml data and adding it to array and display in respectives views,now my problem is am parsing xml and adding those objects it to nsmutablearray as shown below:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
samplearray = [[NSMutableArray alloc]init];
xmlParserObject = [[NSXMLParser alloc] initWithData:webData];
[xmlParserObject setDelegate:self];
[xmlParserObject parse];
for (int i =0; i<[rssOutputData count]; i++) {
NewsList *log = [rssOutputData objectAtIndex:i];
feedid = log.id;
NSLog(#"%d",feedid);
Invit = log.newsletterdet;
NSLog(#"%#",Invit);
[samplearray addObject:log];
NSLog(#"Count Final %d",[self.samplearray count]);
}
[[self navigationController] tabBarItem].badgeValue = mycount2;
NSLog(#"%#",mycount2);
[tblView reloadData];
[connection release];
}
The Above prints Count Value as 2014-04-04 15:21:10.009 cftsversion1[3087:70b] Count Final 1
But when I call those Count in tableview methods, it prints 0 so I cannot load datas in tableview Here is the code I tried for tableview methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
return [samplearray count];Prints 0 here
NSLog(#"Count %d",[samplearray count]); Prints 0 here
if (section == 1)
return 1;
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"eventCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
for (UIView *view in cell.contentView.subviews) {
[view removeFromSuperview];
}
if (indexPath.section == 0)
{
NewsList *msglist = [samplearray objectAtIndex:indexPath.row];
cell.textLabel.text = msglist.newsletterdet;
NSLog(#"%#",msglist.newsletterdet);
NSInteger stat = msglist.readflag;
if ([[SingleTonClass sinlgeTon].colorArray2 containsObject:[NSString stringWithFormat:#"%d",indexPath.row]] || stat == 1) {
cell.textLabel.textColor = [UIColor redColor];
}
else{
cell.textLabel.textColor = [UIColor greenColor];
}
cell.backgroundColor = [UIColor blackColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (indexPath.section == 1)
{
UIButton *viewmoreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
viewmoreButton.frame = CGRectMake(200.0f, 5.0f, 80.0f, 30.0f);
[viewmoreButton setTitle:#"View More" forState:UIControlStateNormal];
[cell addSubview:viewmoreButton];
[viewmoreButton addTarget:self
action:#selector(viewMore:)
forControlEvents:UIControlEventTouchUpInside];
cell.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:viewmoreButton];
}
return cell;
}
When run the above tableview code section 0 is not at all loading because array count prints 0 only section 1 is loading please help me how to solve this issue Thanks in advance
Intialize sampleArray in ViewDidLoad
samplearray = [[NSMutableArray alloc]init]
Make sure [tblView reloadData] is working properly.Initialy table will be loaded before completion of connectionDidFinishLoading, so count will be 0. Only in reload the count increments.
I have doubt you are printing value in wrong way. Try to print it correctly first and update us:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
NSLog(#"Count %d",[samplearray count]);\\ Prints 0 here
return [samplearray count];\\Prints 0 here
}
else if (section == 1)
{
return 1;
}
return 0;
}
and declare your NSMutableArray in .h file like:
#property (nonatomic, strong) NSMutableArray *samplearray;

How to expand and collapse rows at particular level in UITableView?

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

UITableView Data insertion

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

Resources