添加按钮到UITableViewCell的附件视图

LDK*_*LDK 16 uitableview ios

目标:当用户选择单元格时,会向该单元格添加一个按钮.在我的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];
Run Code Online (Sandbox Code Playgroud)

不幸的是,这似乎没有做任何事情.我是否重新绘制细胞校正?我需要以另一种方式添加吗?

BP.*_*BP. 23

尝试使用此代码块而不是上面提供的块:

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

这应该显示按钮,但您仍然需要使用addTarget将某种选择器连接到它.(我不知道,如果在监听的accessoryButtonTappedForRowWithIndexPath代表将在这种情况下工作,首先尝试一下,看看它是否触发您按下按钮.)

  • 实际上,我尝试使用accessoryButtonTappedForRowWithIndexPath方法,但它显然不会触发自定义附件视图按钮. (5认同)
  • 令人惊讶的是,UIButtonTypeRoundedRect似乎是必要的.我尝试了UIButtonTypeCustom,它没有用.+1 (2认同)

Sen*_*ful 9

我有同样的问题.试图将accessoryView设置为具有图像的UIButton导致它不出现.

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


pro*_*rmr 7

将按钮指定为附件视图,而不是附件视图的子视图.

UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryView = downloadButton;
Run Code Online (Sandbox Code Playgroud)

  • 好像什么也没做. (2认同)