效果:
1.定义UITableView的实例,并让当前视图遵守UITableView的两个协议。
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@end
2.初始化tableView,并设置tableView的属性
@implementation ViewController
static NSString *cellIdentifier = @"RecordTableViewCell";
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] init];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.backgroundColor = [UIColor blackColor];
self.tableView registerClass:[RecordTableViewCell class] forCellReuseIdentifier:cellIdentifier];
[self.view addSubview:self.tableView];
[self.tableView setFrame:CGRectMake(tvX, tvY, tvW, tvH)];//坐标大小自己设置
}
RecordTableViewCell是自定义的单元格cell。
3.实现协议中必须要实现的方法
//单元格数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//列表的单元格数,self.records是你保存的数据
return self.records.count;
}
//单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
Record *record = self.records[indexPath.row];
//计算文本所需要的高度
CGSize formulaSize = record.formula.length == 0 ? CGSizeMake(0, 0) : [record.formula boundingRectWithSize:CGSizeMake(tableView.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]} context:nil].size;
CGSize remarkSize = [record.note boundingRectWithSize:CGSizeMake(tableView.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]} context:nil].size;
CGFloat cellHeight = remarkSize.height + formulaSize.height + 10;
//将高度返回就是当前单元格的高度
return cellHeight;
}
//单元格内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//初始化单元格
RecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// 将数据中的值传给单元格
Record *record = self.records[indexPath.row];
cell.formulaText = record.formula;
cell.remarkText= record.note;
return cell;
}
4.一些其他经常使用的方法
#选中某个单元格的操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
//弹出弹窗
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *copyAction = [UIAlertAction actionWithTitle:@"复制该行" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//复制操作
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:copyAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}