我在让我的按钮在表格单元格中的特定 y 值以下工作时遇到了一些问题。我正在使用名为“RowWhiskyContent”的自定义 UITableViewCell 类。默认高度为 44px,低于该高度我的事件似乎不再触发。该按钮显示得很好,该点以下的所有其他内容也显示得很好,但是该事件似乎没有触发。如果我将按钮放在中间位置(比如在 y=35 处),只有按钮的顶部会触发事件,而底部不会执行任何操作。
以下是精简的代码:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = nil;
if(![self createView:&cell])
{
UIImage *bottle = [UIImage imageNamed:@"icon_add.png"]; //image size: 22x22
UIButton *bottleButton = [[UIButton alloc] initWithFrame:CGRectMake(60, 70, bottle.size.width, bottle.size.height)];
[bottleButton setImage:bottle forState:UIControlStateNormal];
[cell.contentView addSubview:bottleButton];
[bottleButton addTarget:self action:@selector(addToCollection:) forControlEvents:UIControlEventTouchUpInside];
cell.contentView.frame = CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, 160);
//cell.frame = cell.contentView.frame; // Tried this, didn't work.
//[tableView reloadData]; // Tried this too, didn't work either.
}
return cell;
}
// Check if cell exists and create the cell if it doesn't.
-(BOOL) createView: (UITableViewCell**) cell
{
BOOL cellExists = YES;
*cell = (RowWhiskyContent *) [myTableView dequeueReusableCellWithIdentifier:@"ContentIdentifier"];
if(*cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RowWhiskyContent" owner:self options:nil];
*cell = [topLevelObjects objectAtIndex:0];
cellExists = NO;
}
return cellExists;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
return 160;
}
因为我将单元格和 contentView 的高度都设置为 160,所以我不确定这里出了什么问题。重新加载数据无效,设置 cell.frame 也无效。
谁能告诉我我做错了什么? 提前致谢。
编辑: 添加了屏幕截图:
红色按钮工作正常,但如果我将它放在绿色按钮的位置,它就会停止工作。 contentview 的背景设置为紫色,以便解释紫色区域。单击单元格时,它会触发 didSelectRowAtIndexPath
,所以我猜单元格本身也足够大。
最佳答案
这绝对是一个内容大小问题。您的按钮将显示在框架外,类似于 CSS 中的溢出,但它们不会响应事件。因此,无论 UIView 包含您的 UIButton,您都需要确保它的内容/框架/边界都设置得足够高。您还可以使用 [cell.contentView sizeToFit] 自动调整它的内容。
绝对不应该在 UITableView 的协议(protocol)方法中重新加载数据。
关于iphone - UITableViewCell 内的事件在 y 值以下不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9427930/