UITableView的使用及代理方法

570 阅读1分钟

在App开放中我们经常会使用到UITabbleView,常用于数据展示。那么使用时不得不引入两个代理方法<UITableViewDataSource,UITableViewDelegate>。 下面我们来简单的创建一个TableView并介绍下其基本属性。 @property (nonatomic,strong) UITableView * myTable; //声明对象 建议使用懒加载的方式创建,可以节省内存,然后再外部请求到数据后用.语法调用。

- (UITableView *)myTable{ if (!_myTable) { _myTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64-44) style:UITableViewStylePlain]; //初始化对象并设定大小和风格样式 _myTable.delegate = self; _myTable.dataSource = self; //设置代理 _myTable.showsHorizontalScrollIndicator = NO; //不显示水平滚动条 _myTable.showsVerticalScrollIndicator = NO; //不显示竖直滚动条 _myTable.bounces = NO; //关闭弹性效果 } return _myTable; }

我们要在UITableView上展示数据,所以要有一个数据源,同理数据源也采用懒加载的方式。 @property (nonatomic,strong) NSMutableArray * dataSorce;

- (NSMutableArray *)dataSorce{ if (!_dataSorce) { _dataSorce = [[NSMutableArray alloc]init]; } return _dataSorce; }

下面开始设置代理方法:


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _dataSorce.count; //返回cell的个数 }


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 40; //返回cell的高度 }


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString * string = @"patrcell"; PartCell * cell = [tableView dequeueReusableCellWithIdentifier:string]; if (!cell) { cell = [[PartCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]; } cell.selectionStyle = UITableViewCellSelectionStyleNone; return cell; //cell的复用及自定义cell的样式 }


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ }