2010-05-14 58 views
2

小背景下,表視圖由一個fetchedResultsController填充,它使用Strings填充表視圖。現在我試圖在每個tableview單元格中的每個字符串旁邊添加一個按鈕。到目前爲止,我一直試圖在configureCell:atIndexPath方法中創建一個按鈕,然後將該按鈕作爲子視圖添加到表格單元格的內容視圖中,但出於某種原因,按鈕不顯示。以下是相關的代碼。如果有人想要更多的代碼發佈,只需要問,我會提出任何你想要的。任何幫助是極大的讚賞。iPhone問題:如何將一個按鈕添加到tableview單元格?

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { 

// get object that has the string that will be put in the table cell 
Task *task = [fetchedResultsController objectAtIndexPath:indexPath]; 

//make button 
UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; 
[button setTitle:@"Check" forState:UIControlStateNormal]; 
[button setTitle:@"Checked" forState:UIControlStateHighlighted]; 

//set the table cell text equal to the object's property 
cell.textLabel.text = [task taskName]; 

//addbutton as a subview 
[cell.contentView addSubview:button]; 
} 

- (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]; 
    } 

// Configure the cell. 
[self configureCell:cell atIndexPath:indexPath]; 
    return cell; 
} 

回答

2

三種意見:

  1. 您可能需要設置UIButton的框架。否則,它不知道它應該有多大以及它應該放在哪裏。它可能帶有一個默認框架,但我沒有調查過。
  2. 你正在泄漏你的按鈕。呼叫後您不需要retain[UIButton buttonWithType:...];
  3. 您可以將多個按鈕添加到同一個單元格。如果您正在重複使用單元格,則應首先調用removeFromSuperview的每個子視圖cell.contentView
+0

感謝您的回覆,我將[UIButton buttonWithType]更改爲 CGRect buttonFrame = CGRectMake(0,0,40,40); UIButton * button = [[UIButton alloc] initWithFrame:buttonFrame]; 但沒有任何顯示。你認爲它可能被某些東西遮擋了嗎? 編輯:它被遮擋了,我可以在其他字符串文本下看到一些文本。現在我只需要移動它。非常感謝您的幫助。 – Jake 2010-05-14 17:41:43

+0

'+ buttonWithType:'是'UIButtons'的正確初始值設定項。你只需要做一些事情:'[button setFrame:CGRectMake(0,0,40,40)];'afterwardswards – 2010-05-14 19:08:32

相關問題