我做了很多测试和搜索,但仍然无法找到我添加到UIButton
中的UITableViewCell.contentView
无效的原因。我可以保证我做的一切都正确,按钮仍然无法回答TouchUpInside
事件。
[self.contentView addSubview:theButton];
但这可行:
[self addSubview:theButton];
正如您所料,self
是UITableViewCell
的子类。并记录到文档,我们不应该总是添加到contentView
?
抱歉我的英语不好。我希望我能清楚地描述它。
答案 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自己,就像我做代码一样。
祝你好运。