[OC]TableView使用

本文指导如何在iOS项目中创建并使用tableView,包括创建TableViewCell类、配置数据源和代理方法,实现基本的列表展示功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个OC项目,因为这是个简单demo,创建tableView的代码就写在ViewController.m里了。

新建一个TableViewCell类,属于UITableViewCell,别忘了xib。

别忘了这俩

把label拖到TableViewCell.h里面

可以开始添加TableView了,在ViewController.m导入TableViewCell.h

实例化一个UITableView的对象_tableView,加上代理和数据源:

初始化一个数组

NSArray *arr = @[@"a",@"b",@"c"];

 写一个创建tableView的方法

-(void)creatTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

在viewDidLoad里调用这个方法

[self creatTableView];

 下面实现tableView的delegate和datasource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return array.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48;
} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellID = @"TableViewCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; if (cell==nil) {
        cell=[[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:self options:nil]lastObject];
    } cell.textLabel.text = arr[indexPath.row]; return cell; }

 运行结果就不贴图了

转载于:https://www.cnblogs.com/ybw123321/p/5403969.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值