您的位置:首页 > 移动开发

FirstApp,iphone开发学习总结8,自定义TablevViewCell

2012-05-07 16:53 441 查看
创建TableViewCell文件(继承于UITableViewCell),在.h文件中添加2个label和一个方法:

@interface TableViewCell : UITableViewCell{
UILabel *nameLbl;
UILabel *ageLbl;
}
- (void)setValue:(NSString *)name age:(NSString *)age; 创建子视图://增加了2个label

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
nameLbl = [[UILabel alloc] initWithFrame:CGRectZero];
[[self contentView] addSubview:nameLbl];
[nameLbl release];

ageLbl = [[UILabel alloc] initWithFrame:CGRectZero];
[[self contentView] addSubview:ageLbl];
[ageLbl release];
}
return self;
} 子视图布局://只做了简单的处理,设置位置、改变字体大小和字体颜色

//此处layoutSubviews方法是得到view的具体大小后,再实现子类布局,这里直接设置了。

- (void)layoutSubviews
{
[super layoutSubviews];
nameLbl.frame = CGRectMake(5.0, 5.0, 20.0, 20.0);
nameLbl.font = [UIFont fontWithName:@"" size:18];
nameLbl.textColor = [UIColor redColor];

ageLbl.frame = CGRectMake(50.0, 5.0, 20.0, 20.0);
ageLbl.font = [UIFont fontWithName:@"" size:12];
ageLbl.textColor = [UIColor blueColor];
} 设置方法://设置

- (void)setValue:(NSString *)name age:(NSString *)age
{
[nameLbl setText:name];
[ageLbl setText:age];
}修改TableViewController.m,添加引用:

#import "TableViewCell.h" 修改- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法:

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

TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[cell setValue:[data objectAtIndex:[indexPath row]] age:[data objectAtIndex:[indexPath row]]];//直接用数字了
return cell;
}

编译运行,已经显示出2个不同颜色的label。

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