通过点击sectionView实现section下属的cell关闭或打开,类似QQ联系人界面的功能。
#import "ViewController.h"#define ALLWIDTH [UIScreen mainScreen].bounds.size.width#define ALLHEIGHT [UIScreen mainScreen].bounds.size.height@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>{ UITableView*tableview; NSArray *dataArr; NSMutableArray *isOpenArr; }@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, ALLWIDTH, ALLHEIGHT-40)]; tableview.delegate =self; tableview.dataSource = self; tableview.tableFooterView = [[UIView alloc]init]; [self.view addSubview:tableview]; dataArr = [NSArray array]; dataArr = @[@"cell1",@"cell2",@"cell3",@"cell4",@"cell5"]; isOpenArr = [NSMutableArray array]; for (int i =0; i< dataArr.count; i++) { [isOpenArr addObject:@"0"]; } }-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 5;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ if([isOpenArr[section] isEqualToString:@"1"]) { return dataArr.count; }else{ return 0; }}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ NSString *cellstr = @"cell"; UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellstr]; if (!cell) { cell = [tableview dequeueReusableCellWithIdentifier:cellstr forIndexPath:indexPath]; } cell.textLabel.text = dataArr[indexPath.row]; return cell;}-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ return 50;}-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ UIView *view =[[UIView alloc]init]; UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,ALLWIDTH, 50)]; lable.text = [NSString stringWithFormat:@"------------第%ld组---------",(long)section]; lable.textColor = [UIColor redColor]; [view addSubview:lable]; //添加点击手势 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(topgesture:)]; [view addGestureRecognizer:tap]; view.tag = section; return view;}-(void)topgesture:(UITapGestureRecognizer*)tap{ NSInteger index = tap.view.tag; if ([isOpenArr[index] isEqualToString:@"1"]) { [isOpenArr replaceObjectAtIndex:index withObject:@"0"]; }else{ [isOpenArr replaceObjectAtIndex:index withObject:@"1"]; } [tableview reloadData]; }-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ [tableview deselectRowAtIndexPath:indexPath animated:YES]; NSLog(@"------================--%ld-----",indexPath.row);}
新闻热点
疑难解答