iOS开发-UITableView自定义Cell
UITableView在iOS中开发的重要地位是毋庸置疑的,基本上应用中用到的比例是一半左右,而且大部分情况都是需要自定义单元格的,这样用户看到的App才能更有美感。之前写过UITableView的基本用法,如果对UITableView不是很熟悉可以参考本人之前的博客,因此很多UITableView的知识点就默认你已经熟悉了,先看下自定义实现的效果,这是自定义的Cell最后展现的效果:
自定义Cell
1.首先新建一个CustomCell.xib文件,方式如下:
2.新建一个继承自UITableViewCell的CustomTableViewCell类,需要重写initWithStyle方法:
1
2
3
4
5
6
7
8
|
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:( NSString *)reuseIdentifier{
self =[ super initWithStyle:style reuseIdentifier:reuseIdentifier];
if ( self ) {
NSArray *views = [[ NSBundle mainBundle] loadNibNamed:@ "CustomCell" owner: nil options: nil ];
self =[views firstObject];
}
return self ;
} |
3.CustomCell.xib中拖入一个UITableViewCell,然后和CustomTableViewCell关联:
关联之后CustomTableViewCell多了一个属性:
1
|
@property (weak, nonatomic ) IBOutlet UILabel *title;
|
UITableView加载Cell
1.viewDidLoad初始化UITableView:
1
2
3
4
|
self .tableView=[[UITableView alloc]initWithFrame:CGRectMake(10, 10,CGRectGetWidth( self .view.bounds)-20, CGRectGetHeight( self .view.bounds)-10)];
self .tableView.delegate= self ;
self .tableView.dataSource= self ;
[ self .view addSubview: self .tableView];
|
2.初始化标题数组travelArr:
1
2
3
4
|
-( NSArray *)travelArr{
[email protected][@ "北京-清迈" ,@ "北京-香港" ,@ "北京-东京" ,@ "北京-大阪" ,@ "北京-新加坡" ,@ "北京-维多利亚" ,@ "北京-纽约" ,@ "北京-夏威夷" ,@ "北京-维多利亚" ,@ "北京-柬埔寨" ];
return _travelArr;
} |
3.实现UITableViewDataSource中的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
-( NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
} -( NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:( NSInteger )section{
return [ self .travelArr count];
} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath{
CustomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell== nil ) {
cell=[[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.title.text=[ self .travelArr objectAtIndex:indexPath.row];
return cell;
} |
4.实现UITableViewDelegate中的方法:
1
2
3
4
|
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:( NSIndexPath *)indexPath{
UITableViewCell *cell = [ self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
} |
简单的自定义大概就是如此了,如果有所收获,帮忙推荐下~
本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4457350.html,如需转载请自行联系原作者