UITableView 的项目运用

本文详细介绍如何在iOS应用中实现一个完整的TableView,包括初始化TableView、设置cell样式、定义cell数量及高度,并展示了如何添加section头部视图。

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

前面写了一个最简单的tableview,现在教大家在项目中运用的最多的tableview,废话不多说,上图


首先,写一个tableview的属性  :

@property (nonatomic,strong)UITableView *tableView;


初始化

- (UITableView *)tableView{

    if (!_tableView) {

        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 375, 500) style:UITableViewStylePlain];

        _tableView.dataSource = self;

        _tableView.delegate = self;

//这里如果不需要cell的虚线可以加上这句话:

_tableView.separatorStyle UITableViewCellSeparatorStyleNone;

    }

    return _tableView;

}


其次,最重要的cell的初始化:

这里说明一下cell的风格:一共四种,大家可以自己写来看一下有什么不同

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (!cell) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];

    }

    cell.textLabel.text = @"这是一个cell";

    return cell;

}


当然,现在设置cell的高度以及数量

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 5;

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 35;

}



如果你只是需要一个简单的cell,那么到这里,就可以了,

但实际项目中网网这些是不够的,下面我们设置tableview每一section之间的headview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 3;  

//这里设置一共有几个section,这里说明一下,我们上面设置的cell的数量是在section下面的数量,这里设置了section有3个,那么说明每一个section下面的cell都有5个(上面设置的cell数量)

}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 10; //这里设置的是你的head view的高度

}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *view = [UIView new];

    view.backgroundColor = [UIColor blackColor];

    return view;  //这个view设置的就是headview,这里可以在这个view上面添加文字,图片等等

}


//好了,到此为止,一个tableview就设置好了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值