动态可扩展和折叠表视图单元格?

时间:2018-02-21 05:18:47

标签: ios objective-c uitableview expandablelistview

我开发了可扩展和折叠的表视图,用于来自服务器的动态数据。我已成功在标题视图中显示州名,但我无法显示与州名相关的地区的子数据。

我按照此http://www.iostute.com/2015/04/expandable-and-collapsable-tableview.html

的链接

我的数据是

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

我的代码是

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委托

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

}

2 个答案:

答案 0 :(得分:1)

我有两个解决方案

(1)最初你将numberofrow放在任何部分为零,点击任何部分后你可以为点击部分添加行。

(2)部分的数量为1,你需要使用两个单元格&#34; cellwithheaderonly&#34;和&#34; cellwithheaderandsubpart&#34;最初你会使用&#34; cellwithheaderonly&#34;当用户点击你需要使用的任何单元格时,&#34; cellwithheaderandsubpart&#34;

您可以参考以下网址

Expanding and Collapsing table view cells in ios

https://www.anexinet.com/blog/expandable-collapsible-uitableview-sections/

答案 1 :(得分:1)

您必须维护下面给出的数组: -

lat arr = [[“name”:”firstRow” , “subRowArray”:[1,2,3,4]],[“name”:”secondRow” , “subRowArray”:[1,2,3,4]],[“name”:”thirdRow” , “subRowArray”:[1,2,3,4]]]

然后根据您的数组展开和折叠。 如果您想使用库,请转到expendable Tableview