iphone sdk:我如何在uitableviewCell上添加一个按钮?

时间:2010-10-08 21:05:28

标签: iphone objective-c uitableview

我正在尝试向uitableviewcell添加一个按钮,我无法让它工作任何建议我做错了什么?

checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[checkButton setFrame:CGRectMake(0, 0, 30, 30)];
[checkButton setBackgroundImage:[[UIImage imageNamed:@"checked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[checkButton setBackgroundImage:[[UIImage imageNamed:@"checked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateSelected];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    [cell addSubview:checkButton];

}
NSArray *tempArray = [[exerciseNames objectAtIndex:indexPath.section] objectForKey:@"rowValues"];
[cell addSubview:checkButton];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.text = [NSString stringWithFormat:@"%@ (%@)", [[tempArray objectAtIndex:indexPath.row] objectForKey:@"full"], [[tempArray objectAtIndex:indexPath.row] objectForKey:@"short"]];

// Set up the cell...

return cell;
}

2 个答案:

答案 0 :(得分:2)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UIButton* checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[checkButton setFrame:CGRectMake(0, 0, 30, 30)];
[checkButton setBackgroundImage:[[UIImage imageNamed:@"checked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[checkButton setBackgroundImage:[[UIImage imageNamed:@"checked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateSelected];
[cell addSubview:checkButton];

[checkButton release];

NSArray *tempArray = [[exerciseNames objectAtIndex:indexPath.section] objectForKey:@"rowValues"];

cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.text = [NSString stringWithFormat:@"%@ (%@)", [[tempArray  objectAtIndex:indexPath.row] objectForKey:@"full"], [[tempArray objectAtIndex:indexPath.row] objectForKey:@"short"]];

// Set up the cell...

return cell;
}

这样按钮就会添加到单元格&释放自己的内存,以免内存泄漏问题

您还可以在单​​元格内容视图中添加按钮,而不是在单元格中添加按钮

例如

[cell.contentView addSubview: showButton];

答案 1 :(得分:1)

您必须为每个单元格创建一个新的按钮实例,您不能使用共享实例。视图一次只能放在一个地方。