以编程方式进行:
自定义单元格.h
#import <UIKit/UIKit.h>
@interface CustomCell : UITableViewCell
{
UILabel *firstName;
UILabel *lastName;
}
@property (nonatomic, retain) UILabel *firstName;
@property (nonatomic, retain) UILabel *lastName;
@end
CustomCell.m
#import "CustomCell.h"
@implementation CustomCell
@synthesize firstName, lastName;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
firstName = [[UILabel alloc]init];
firstName.textAlignment = UITextAlignmentLeft;
firstName.font = [UIFont boldSystemFontOfSize:18];
firstName.backgroundColor = [UIColor clearColor];
lastName = [[UILabel alloc]init];
lastName.textAlignment = UITextAlignmentLeft;
lastName.font = [UIFont boldSystemFontOfSize:14];
lastName.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:firstName];
[self.contentView addSubview:lastName];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+7 ,7, 240, 20);
firstName.frame = frame;
frame= CGRectMake(boundsX+125 ,25, 220, 20);
lastName.frame = frame;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
- (void)dealloc
{
[firstName release];
[lastName release];
[super dealloc];
}
@end
在带有 TableView 的 ViewAController 中,不要忘记导入 CustomCell.h
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
if (indexPath.section == 0) {
cell.firstName.text = @"firstname";
// and or cell.firstName.frame = ...
} else {
cell.lastName.text = @"lastname"
// and or cell.lastName.frame = ...
}
return cell;
}