在暑假的项目里我已经写过了折叠cell,但是那个cell的内容的变更只是使用label,因此这次我又一次学习了折叠cell,使用了可变数组来改变cell的单元格的内容,这样,通过点击单元格就可以实现cell的打开与关闭。
首先,我创建了两个属性,一个单元格一个可变数组,然后单元格的内容是按照数组的元素顺序排列的,当点击单元格的时候,实际上是改变了数组的元素顺序,来以此改变单元格的内容。
代码如下:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.arr = [NSMutableArray arrayWithObjects:@"a", @"b", @"c", @"d", @"e", nil];
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.frame = CGRectMake(30, 100, 250, 100);
self.tableView.pagingEnabled = NO;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"id"];
[self.view addSubview:self.tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"id"];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.textLabel.text = self.arr[indexPath.row];
cell.backgroundColor = [UIColor orangeColor];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0) {
if (self.tableView.bounds.size.height == 100) {
self.tableView.frame = CGRectMake(30, 100, 250, 500);
} else {
self.tableView.frame = CGRectMake(30, 100, 250, 100);
}
} else {
NSString *str = [NSString stringWithFormat:@"%@",self.arr[indexPath.row]];
[self.arr replaceObjectAtIndex:indexPath.row withObject:self.arr[0]];
[self.arr replaceObjectAtIndex:0 withObject:str];
[self.tableView reloadData];
}
}
@end
最终效果: