为什么UITableViewCell.contentView中的UIButton不起作用?

时间:2011-11-17 03:04:27

标签: ios uitableview uibutton

我做了很多测试和搜索,但仍然无法找到我添加到UIButton中的UITableViewCell.contentView无效的原因。我可以保证我做的一切都正确,按钮仍然无法回答TouchUpInside事件。

像这样的代码不起作用:

[self.contentView addSubview:theButton];

但这可行:

[self addSubview:theButton];

正如您所料,selfUITableViewCell的子类。并记录到文档,我们不应该总是添加到contentView

抱歉我的英语不好。我希望我能清楚地描述它。

2 个答案:

答案 0 :(得分:1)

在cellForRowAtIndexPath方法中尝试此代码

UIButton *scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
scanQRCodeButton.frame = CGRectMake(260.0f, 6.0f, 45.0f, 25.0f);
scanQRCodeButton.backgroundColor = [UIColor whiteColor];
[scanQRCodeButton setTitle:@"button" forState:UIControlStateNormal];    
[cell.contentView addSubview:scanQRCodeButton];

它会起作用。

答案 1 :(得分:0)

如果您的UITableViewCell具有客户高度(不是默认的44.0f)。 如果是这样,你应该设置如下代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.contentView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForRowAtIndexPath:indexPath]);
        // add a UIButton that you create
    }
    return cell;
}

出现此问题的原因是cell.contentView.size是默认值(320.f,44.0f),如果您的按钮位于rect上,则该按钮无法接受该事件,因此您应该设置该单元格。 contentView.frame自己,就像我做代码一样。

祝你好运。