Objective-C 学习记录 - 20

本文详细介绍如何使用UITableView展示数据,包括设置数据源、定义各部分显示内容等关键步骤。通过实现UITableViewDataSource协议,开发者可以轻松地为UITableView提供所需的数据并定制其外观。

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

1.UITableView 展示数据的方法
需要设置UITableViewDataSource协议,UITableView会自动向dataSource请求数据

self.tableView.dataSource = self;

/** 告诉tableView一共有多少组数据 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

/** 告诉tableView第section组有多少行 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    } else {
        return 6;
}

/** 告诉tableView每一行显示的内容(tableView每一行都是UITableViewCell或者它的子类) */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] init];
    if (indexPath.section == 0){  //第0组
        if (indexPath.row == 0){  //第0行
            cell.textLabel.text = @“要显示的文字”;  //文字
            cell.imageView.image = [UIImage imageNamed:@“图片的名字”];  //图片
            cell.accessoryType = UITableViewCellAccessoryCheckmark;  //设置cell右边的指示样式
            cell.accessoryView = [[UISwitch alloc] init];  //设置cell右边显示的控件,优先级大于accessoryType
        }
    }
    return cell;
}

/** 告诉tableView每一组的头部标题 */
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @“第一组的头部标题”;
    } else {
        return @“其他组的头部标题”;
    }
}

/** 告诉tableView每一组的尾部标题 */
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return @“第一组的尾部标题 ”;
    } else {
        return @“其他组的尾部标题 ”;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值