UITableView--区折叠

UITableView的cell折叠

#import"ViewController.h"

#import"customTableViewCell.h"

@interfaceViewController() {

UITableView* table;

BOOLflag [3];

}

@end

@implementationViewController

//释放全局变量

- (void)dealloc {

[table release];

//继承父类

[super dealloc];

}

- (void)viewDidLoad {

[super viewDidLoad];

//全局的UITableView

table= [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStyleGrouped];

//UITableView代理

table.delegate=self;

table.dataSource=self;

//第二种注册方式记得创建继承于UITableViewCell的类下面创建cell时要注意类名称

[table registerClass:[customTableViewCellclass] forCellReuseIdentifier:@"cell"];

//系统自动偏移属性

self.automaticallyAdjustsScrollViewInsets=NO;

//添加

[self.view addSubview:table];

}

//返回区

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {

return3;

}

//返回行

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {

//默认折叠开关是关闭状态

if(flag[section] ==NO) {

//关闭状态下行数为0

return0;

}else{

//点击打开后行数为5

return5;

}

}

//重用机制方法

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

//出列。由于使用注册,所以不需要判断if(!cell)

customTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

//行文本内容

cell.textLabel.text= [NSString stringWithFormat:@"%ld--%ld",indexPath.section,indexPath.row];

//行最右配件

cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

return cell;

}

//区头名称可不写

- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section {

return@"区头";

}

//区头加载视图

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {

//创建视图不要写添加。return view;这一句就是默认添加

UIView* view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)] autorelease];

//写button

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

btn.frame=CGRectMake(0, 0, 44, 44);

//绑定方法要传参

[btn addTarget:selfaction:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

//设置tag值

btn.tag= section + 10 ;

[view addSubview:btn];

//[btn release];不写否则运行时系统会崩溃,出作用域{}时会自动释放一次。

//设置图片视图

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"a"]];

imgView.frame=CGRectMake(0, 0, 44, 44);

[view addSubview:imgView];

[imgView release];

//设置图片视图的动画

if(flag[section] ==NO) {

imgView.transform=CGAffineTransformIdentity;

}else{

//设置图片顺时针旋转45°

imgView.transform=CGAffineTransformMakeRotation(M_PI_2);

}

return view;

}

- (void)btnClick:(UIButton*)btn {

//检验测试用的输出可不写

NSLog(@"btnClick");

NSLog(@"%ld",btn.tag);

//点击取反按钮状态

flag[btn.tag- 10] = !flag[btn.tag- 10];

//检验测试用的输出可不写

NSLog(@"%ld",btn.tag);

//NSIndexSet:索引的集合其中的参数是想要刷新的区的集合

//用区创建一个集合集合的元素就是区号012

NSIndexSet *set = [NSIndexSet indexSetWithIndex:btn.tag- 10];

//行的动画

[table reloadSections:set withRowAnimation:UITableViewRowAnimationFade];

}

@end

你可能感兴趣的:(UITableView--区折叠)