小工具知识网

当前位置: 首页 > 行业知识 > iOS-折叠cell

行业知识

iOS-折叠cell

2026-11-30 14:25:34 来源:互联网转载

折叠cell

���叠cell即可以实现单元格的收起和展开

思路:通过按钮的事件函数来控制tableview的高度,当按钮未被选中时,只显示一行即tableview的尺寸高度为一行的高度,当按钮被选中时,显示展开后的所有单元格的信息,即tableview的高度为所有单元格的高度。

代码如下:

先定义三个属性,用可变数组来存储单元格的信息,从而使自定义cell的不同行显示不同的信息。

@property (nonatomic, strong) UITableView* tableView;@property (nonatomic, strong) NSMutableArray* foldArray;@property (nonatomic, strong) UIButton* button;
   _foldArray = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(10,100,380,50) style:UITableViewStylePlain];    _tableView.delegate = self;    _tableView.dataSource = self;    _tableView.userInteractionEnabled = YES;    _tableView.separatorColor = [UIColor redColor];    [self.view addSubview:_tableView];    _arrayData = [[NSMutableArray alloc] init];    [_tableView registerClass:[FirstTableViewCell class] forCellReuseIdentifier:@"first"];    _button = [UIButton buttonWithType:UIButtonTypeCustom];    [_button setTitle:@"点击展开" forState:UIControlStateNormal];    [_button setTitle:@"点击收起" forState:UIControlStateSelected];    [_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];    [_button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];    _button.backgroundColor = [UIColor yellowColor];    _button.titleLabel.font = [UIFont systemFontOfSize:20];    [_button addTarget:self action:@selector(pressButton:) forControlEvents:UIControlEventTouchUpInside];    _button.frame = CGRectMake(0, 0,380, 50);    [self.tableView addSubview:_button];    // Do any additional setup after loading the view.}//用存储信息的数组长度确定组数- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return _foldArray.count;}- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return  1;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    FirstTableViewCell* cell = [_tableView dequeueReusableCellWithIdentifier:@"first" forIndexPath:indexPath];    //第一行显示按钮    if (indexPath.row == 0) {        [cell.contentView addSubview:_button];    } else {    //其他行显示需要显示的信息        cell.firstNameLable.text = _foldArray[indexPath.row-1];        cell.userInteractionEnabled = YES;    }    return cell;}- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {        return 50;}- (void)pressButton:(UIButton*)button {    if (button.selected == YES) {        button.selected = NO;        _tableView.frame = CGRectMake(10,100, 380, 50);    } else if (button.selected == NO) {        button.selected = YES;_tableView.frame = CGRectMake(10,100, 380, 50 * _foldArray.count);    }}

实现效果

上一篇:征途怎么改服务器?

下一篇:未备案服务器怎么上传?