将button添加到UITableViewCell的附件视图

目标:当用户select一个单元格时,一个button被添加到该单元格。 在我didSelectRowAtIndexPath函数我有以下内容:

UIButton *downloadButton = [[UIButton alloc] init]; downloadButton.titleLabel.text = @"Download"; [downloadButton setFrame:CGRectMake(40, 0, 100, 20)]; [[self.tableView cellForRowAtIndexPath:indexPath].accessoryView addSubview:downloadButton]; [[self.tableView cellForRowAtIndexPath:indexPath].accessoryView setNeedsLayout]; [downloadButton release]; 

不幸的是,似乎没有做任何事情。 我正在重画细胞修正? 我需要另外添加吗?

试试这个代码块,而不是你上面提供的块:

 UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [downloadButton setTitle:@"Download" forState:UIControlStateNormal]; [downloadButton setFrame:CGRectMake(0, 0, 100, 35)]; [tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton; 

这应该显示button,但你仍然需要使用addTarget挂钩某种select器。 (我不确定是否在这种情况下侦听accessoryButtonTappedForRowWithIndexPath委托会起作用,请先尝试一下,看看它是否触发button按下。)

将该button指定为附件视图,而不是附件视图的子视图。

 UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; cell.accessoryView = downloadButton; 

我有同样的问题。 试图将accessoryView设置为一个UIButton,其中有一个图像导致它不会出现。

诀窍是调用[UIButton sizeToFit] ,以确保其框架设置正确。

尝试这个:

 [[self.tableView cellForRowAtIndexPath:indexPath].contentView addSubview:downloadButton]; 

并且请记住在单元重新使用时删除该button。

这是我的例子,为您的请求提供完整的解决scheme:

在我的UITableViewCell子类(我称之为RNWNewItemCell)中:

 -(void)configureCell... { // create the button self.btnSeekDuplicate = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)]; // just make it yellow until we get our real image.. self.btnSeekDuplicate.backgroundColor = [UIColor yellowColor]; // add the handler for the button press [self.btnSeekDuplicate addTarget:self action:@selector(seekDuplicateButtonWasPressed) forControlEvents:UIControlEventTouchUpInside]; // make it visible in the table cell... [self setAccessoryView:self.btnSeekDuplicate]; } - (void)seekDuplicateButtonWasPressed { do something... } 

在我使用单元格的表代码…

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... RNWNewItemCell *aNewItemCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierForNewItemCell forIndexPath:indexPath]; [aNewItemCell configureCell...] ... } 

请注意,当您设置表格单元的accessoryView时,不会调用accessoryButtonTappedForRowWithIndexPath。 可能是因为他们认为你正在使用对事件做出响应的视图。

它总是最好添加任何你添加到单元cell.contentView 。 另外尝试检查accessoryView是否为零。

迅速

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let accessoryButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton cell.accessoryView = accessoryButton return cell } 

用这个 :

 cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton; 
 let button = UIButton(type:.roundedRect) button.setTitle("A", for: .normal) button.sizeToFit() cell.accessoryView = button