您的位置:首页 > 产品设计 > UI/UE

IOS 表视图(UITableVIew)的使用方法(4)自定义表视图单元

2014-04-17 11:14 537 查看
UITableViewCell的自定义往往需要自建一个UITableViewCell的子类后进行作业。开发者可以选择通过xib或者直接在UITableViewCell的布局中进行UITableViewCell的自定义。这节会采用更直观易懂的xib方式。

(1)新建一个UITableViewCell的子类取名为CustomCell,并且为CustomCell类勾选“xib文件的关联”,CustomCell的xib设计如图所示:


注意:灰色的右箭头不是我们拖入的控件,而是UITableView的属性配置。在新建俩个类文件HBCustomCell.h和HBCustomCell.m,在CumtomView.xib中,把tableViewCell的类选定为HBCustomCell,如图:


在storyboard 中,在tableviewcontroller中,点击tableviewCell,让其类也写成HBCustomCell

(2)完成CustomCell的声明和基本内容撰写。

#import <UIKit/UIKit.h>

@interface HBCustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *playerNumber;
@property (weak, nonatomic) IBOutlet UILabel *playerName;
@property (weak, nonatomic) IBOutlet UILabel *playerRole;
@property (weak, nonatomic) IBOutlet UIImageView *playerPhoto;


(3)完成TableViewController的声明和基本内容撰写

新建一个继承自SimpleTabelViewController的子类名为CustomLayoutViewController。本节考虑让UITableViewCell 可以响应点击事件,并且自定义一切UITableViewCell的信息,所以需要重写initUI方法。

-(void)initUI
{
[super initUI];

//表单元可点击
self.tableView.allowsSelection = YES;
//表单元高度
self.tableView.rowHeight = 44.0f;
}


(4)完成自定义行单元的现实工作

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"customTableViewCellId";

HBCustomCell *cell = (HBCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *arrNib=[[NSBundle mainBundle]loadNibNamed:@"CustomView" owner:self options:nil];
if(arrNib)
{
//第一个元素就是需要的UITableViewCell
cell=(HBCustomCell *)[arrNib objectAtIndex:0];
}
}

//配置UITableViewCell
HBPlayerInfo *onePlayer=[self.datasource objectAtIndex:indexPath.row];
if(onePlayer)
{
cell.playerName.text=onePlayer.name;
cell.playerRole.text=onePlayer.role;
cell.playerNumber.text=[NSString stringWithFormat:@"No.%@",onePlayer.number];
cell.playerPhoto.image=[UIImage imageNamed:@"gaolin.jpeg"];
}
return cell;
}


这里对于xib的读取并不像UIViewController提供的接口那样,而是使用最直接的xib读取方式loadNibNamed,这个方法成功后往往会得到一个xib中所有主要元素的列表

(5)完成点击事件的响应

UITableViewCell收到事件后会通过代理回调函数通知到代理对象处,所以开发者需要实现代理函数如下:

#pragma mark -
#pragma mark Table View delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//反选
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];

//做些响应的事情
HBPlayerInfo *onePlayer = [self.datasource objectAtIndex:indexPath.row];
NSString *str=[NSString stringWithFormat:@"我是:%@", onePlayer.name];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"嗨!" message:str delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
}

//蓝色右箭头的点击事件
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
[self tableView:tableView didSelectRowAtIndexPath:indexPath];
}


运行程序如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: