2018-01-28 iOS基础-小的Demo--点击section隐藏或者显示row

2018-01-28 iOS基础-小的Demo--点击section隐藏或者显示row_第1张图片


在TableViewController里面实现

定义两个属性:

// 数据源数组  用来存储要展示的数据

@property (strong, nonatomic) NSMutableArray *dataArray;

// 记录收缩状态  对应的把每个区的展开收缩记录下来

@property (strong, nonatomic) NSMutableDictionary *dataDic;

这里给一个展示数据:// 用一组假的数据放到 tableview上面self.dataArray = [@[@[@"詹姆斯",@"韦德",@"安东尼"],@[@"赵四",@"谢广坤",@"刘能"],@[@"骚军",@"蓬勃",@"成龙大哥"],@[@"小三",@"小四",@"小五"]] mutableCopy];// 初始化用于标记某一个分区的section的折叠状态的字典self.dataDic = [NSMutableDictionarydictionary];//self.dataDic = [@{@"0":@"1",@"1":@"1",@"2":@"1",@"3":@"1"} mutableCopy];// 这里可以给对应的区一个初始状态,也可以不设置,因为会在点击section的方法中进行赋值// 返回分区数```code- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {returnself.dataArray.count;}```// 判断到底是正常显示row还是row不显示(返回0行)  这里是 等于 0(字符串类型)的时候 展开```code- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {// 取出字典中的 section 如果是第 0 个分区 那么就返回该分区的数据if([[self.dataDic valueForKey:[NSStringstringWithFormat:@"%ld",section]] isEqualToString:@"0"])    {NSLog(@"----------------");return[self.dataArray[section] count];    }else{NSLog(@"**************");return0;    }}```// 设置cell上显示的内容```code- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"forIndexPath:indexPath];cell.backgroundColor = [UIColorcolorWithRed:(arc4random()%173)/346.0+0.5green:(arc4random()%173)/346.0+0.5blue:(arc4random()%173)/346.0+0.5alpha:1];cell.textLabel.text =self.dataArray[indexPath.section][indexPath.row];returncell;}```// 在返回头视图的方法里面给每个区添加一个button```code- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section{// 把分区的头视图设置成ButtonUIButton*button =[UIButtonbuttonWithType:(UIButtonTypeCustom)];    button.backgroundColor = [UIColorredColor];// 设置Button的标题作为section的标题用[button setTitle:[NSStringstringWithFormat:@"第 %ld 组",section] forState:(UIControlStateNormal)];// 设置点击事件[button addTarget:selfaction:@selector(buttonAction:) forControlEvents:(UIControlEventTouchDown)];// 给定tag值用于确定点击的对象是哪个区button.tag = section +1000;returnbutton;}```// 设置Button的点击事件```code- (void)buttonAction:(UIButton*)sender{NSIntegertemp = sender.tag -1000;// 修改 每个区的收缩状态  因为每次点击后对应的状态改变 temp代表是哪个sectionif([[self.dataDic valueForKey:[NSStringstringWithFormat:@"%ld",temp]]isEqualToString:@"0"] )    {        [self.dataDic setObject:@"1"forKey:[NSStringstringWithFormat:@"%ld",temp]];    }else{      [self.dataDic setObject:@"0"forKey:[NSStringstringWithFormat:@"%ld",temp]];}// 更新 section[self.tableView reloadSections:[NSIndexSetindexSetWithIndex:temp] withRowAnimation:(UITableViewRowAnimationFade)];  }```

作者:云之君兮鹏

链接:https://www.jianshu.com/p/e9c2e9fb6565

來源:

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(2018-01-28 iOS基础-小的Demo--点击section隐藏或者显示row)