UITableViewCell 中的 UIButton 不可点击

Posted

技术标签:

【中文标题】UITableViewCell 中的 UIButton 不可点击【英文标题】:UIButton not clickable in UITableViewCell 【发布时间】:2014-08-15 06:44:00 【问题描述】:

我在UITableViewCell 中添加了多个按钮,并用工具栏包裹,但所有按钮都不可点击,一旦我将按钮拖到表格视图的外部,它就已经可以点击了。

这是我的示例应用和场景的屏幕截图:

按钮 1 不可点击,但按钮 2 可点击,已勾选启用用户交互。

【问题讨论】:

请提供您的 cellForRowAtIndexPath 代码... @RamaniAshish 但即使我尝试创建一个新的表格视图控制器,里面只有一个按钮,而 cellForRowAtIndexPath 只返回UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];,里面的按钮也不能点击。 那个按钮的 IBAction 在哪里...? 我建议您创建自定义 UITableViewCell 并且不要忘记像 Ramani 所说的那样操作按钮。 @RamaniAshish 我确实尝试仅使用 NSLog 创建 IBAction,但也没有任何结果,如果将按钮放在表格视图的外部,那么它已经在工作了。 【参考方案1】:

好的,已经发现问题了,是我自己的错误,这是因为我将tableViewCell“启用用户交互”设置为NO,因为我想禁用表格视图默认行选择。

所以我需要将每一层视图“启用用户交互”设置为YES,然后按钮现在可以点击了,感谢所有回复!

【讨论】:

【参考方案2】:

viewForHeaderInSection 中创建你的按钮,像这样..

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [sectionView addSubview:btn];

    //add other subviews to section viewww..

    //return
    return sectionView;


- (void) btnClicked

    //do your thing here..

【讨论】:

【参考方案3】:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

cell.button.tag = indexPath.row
cell.button.addTarget(self, action: "btnClicked:", forControlEvents: .TouchUpInside)


【讨论】:

继续添加 target ,这将使您的 btnClicked 调用多次。

以上是关于UITableViewCell 中的 UIButton 不可点击的主要内容,如果未能解决你的问题,请参考以下文章