//创建一个新类继承tableviewcell,覆写下列函数,用代码创建控件
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];if (self) {
// Initialization code
CGRect nameLabelRect = CGRectMake(0, 5, 70, 15);
UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];nameLabel.textAlignment = UITextAlignmentRight;
nameLabel.text = @"Name:";
nameLabel.font = [UIFont boldSystemFontOfSize:12];[self.contentView addSubview: nameLabel];
CGRect colorLabelRect = CGRectMake(0, 26, 70, 15);
UILabel *colorLabel = [[UILabel alloc] initWithFrame:colorLabelRect];colorLabel.textAlignment = UITextAlignmentRight;
colorLabel.text = @"Color:";
colorLabel.font = [UIFont boldSystemFontOfSize:12];
[self.contentView addSubview: colorLabel];
CGRect nameValueRect = CGRectMake(80, 5, 200, 15);UILabel *nameValue = [[UILabel alloc] initWithFrame:
nameValueRect];nameValue.tag = kNameValueTag;
[self.contentView addSubview:nameValue];
CGRect colorValueRect = CGRectMake(80, 25, 200, 15);UILabel *colorValue = [[UILabel alloc] initWithFrame:
colorValueRect];colorValue.tag = kColorValueTag;
[self.contentView addSubview:colorValue];
}
return self;
}
//重写一下setter
//数据就像这样
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSDictionary *row1 =[[NSDictionary alloc] initWithObjectsAndKeys:@"MacBook", @"Name", @"White", @"Color", nil];
NSDictionary *row2 =[[NSDictionary alloc] initWithObjectsAndKeys:@"MacBook Pro", @"Name", @"Silver", @"Color", nil];
NSDictionary *row3 =[[NSDictionary alloc] initWithObjectsAndKeys:@"iMac", @"Name", @"Silver", @"Color", nil];
NSDictionary *row4 =[[NSDictionary alloc] initWithObjectsAndKeys:@"Mac Mini", @"Name", @"Silver", @"Color", nil];
NSDictionary *row5 =[[NSDictionary alloc] initWithObjectsAndKeys:@"Mac Pro", @"Name", @"Silver", @"Color", nil];
self.computers = [[NSArray alloc] initWithObjects:row1, row2, row3, row4, row5, nil];
}
//显示cell就是这样
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellTableIdentifier = @"CellTableIdentifier";
BIDNameAndColorCell *cell = [tableView dequeueReusableCellWithIdentifier:CellTableIdentifier];
if (cell == nil) {
cell = [[BIDNameAndColorCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellTableIdentifier];
}
NSUInteger row = [indexPath row];
NSDictionary *rowData = [self.computers objectAtIndex:row];
cell.name = [rowData objectForKey:@"Name"]; cell.color = [rowData objectForKey:@"Color"];
return cell;
}