2010-10-08 62 views
0

我想添加一個按鈕到uitableviewcell,我只是不能得到它的工作任何建議我做錯了什麼?iphone sdk:我如何添加一個按鈕到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; 
} 

回答

1

您必須爲每個單元格創建按鈕的新實例,但不能使用共享實例。視圖一次只能在一個地方顯示。

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]; 
相關問題