之前在写share的时候遇到了折叠cell的问题,当时没有解决这个问题,回过头来看看如何实现cell的折叠
前言
这个cell是没有展开的样子
这个是cell点击展开后的样子
一、基本思路
- 使用数组将cell上需要显示的内容存储起来
- 定义一个TableViewCell来实现cell的内容显示
- 在UIVierwController上添加一个大小合适的UITableView,在这个UITableView上显示cell的内容
- 在UITableView的旁边添加一个UIButton到UIViewController上
- 点击UIButton的时候显示所有cell,button关闭的时候显示一行cell
二、代码
//
// ViewController.h
// 折叠cell
//
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
<UITableViewDelegate,
UITableViewDataSource>
@property (nonatomic, strong)UITableView* tableView;
//这里将Button和Array都写成了属性,在下边的代码中会解释原因
@property (nonatomic, strong)UIButton* button;
@property NSMutableArray* strArray;
@end
// ViewController.m
// 折叠cell
//
// Created by 王璐 on 2022/9/3.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//tableview的初始化
_tableView = [[UITableView alloc] init];
_tableView.frame = CGRectMake(200,100,100,25);
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"111"];
//向数组里添加需要显示的cell的内容
_strArray = [[NSMutableArray alloc] init];
[_strArray addObject:@"111"];
[_strArray addObject:@"222"];
[_strArray addObject:@"333"];
[_strArray addObject:@"444"];
//cell的折叠按钮
_button = [[UIButton alloc] init];
_button.frame = CGRectMake(300, 100, 30, 30);
[_button setImage:[UIImage imageNamed:@"关闭.png"] forState:UIControlStateNormal];
[_button addTarget:self action:@selector(pressBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
// Do any additional setup after loading the view.
}
//是否折叠的按钮点击函数
- (void)pressBtn{
if (_button.selected == NO){
self.tableView.frame = CGRectMake(200, 100, 100, 100);
[_button setImage:[UIImage imageNamed:@"打开.png"] forState:UIControlStateNormal];
_button.selected = YES;
} else{
self.tableView.frame = CGRectMake(200, 100, 100, 25);
[_button setImage:[UIImage imageNamed:@"关闭.png"] forState:UIControlStateNormal];
_button.selected = NO;
}
[_tableView reloadData];
}
//cell的行数
//这里用到了button,所以这个button必须写成属性
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (_button.selected == NO){
return 1;
} else{
return 5;
}
}
//cell的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 25;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewcell* cell = [tableView dequeueReusableCellWithIdentifier:@"111"];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"111"];
}
//这里需要把数组的内容显示到cell上,所以这个数组也需要是属性
cell.textLabel.text = _strArray[indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:20];
return cell;
}
@end
添加相对应地图片后即可实现cell的折叠。