Ios 为什么UITableViewCell.contentView中的UIButton获胜';不行?
我做了很多测试和搜索,仍然找不到为什么我添加到Ios 为什么UITableViewCell.contentView中的UIButton获胜';不行?,ios,uitableview,uibutton,Ios,Uitableview,Uibutton,我做了很多测试和搜索,仍然找不到为什么我添加到UITableViewCell.contentView中的UIButton无法工作。我可以保证我做的一切都是对的,按钮仍然不会响应TouchUpInside事件 这样的代码不起作用: [self.contentView addSubview:theButton]; 但这是可行的: [self addSubview:theButton]; 正如您所料,self是UITableViewCell的一个子类。并记录到文档中,我们是否应该总是将内容添加到c
UITableViewCell.contentView
中的UIButton
无法工作。我可以保证我做的一切都是对的,按钮仍然不会响应TouchUpInside
事件
这样的代码不起作用:
[self.contentView addSubview:theButton];
但这是可行的:
[self addSubview:theButton];
正如您所料,self
是UITableViewCell
的一个子类。并记录到文档中,我们是否应该总是将内容添加到contentView
对不起,我的英语很差。我希望我能清楚地描述它。在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];
它会起作用。在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];
如果您的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上方,则按钮无法接受事件,因此应自行设置cell.contentView.frame,就像我编写代码一样
祝您好运。如果您的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上方,则按钮无法接受事件,因此应自行设置cell.contentView.frame,就像我编写代码一样
祝你好运。添加内容时内容视图是否为零?添加内容时内容视图是否为零?