简体   繁体   English

UIButton在TableView单元格中不起作用

[英]UIButton not working in tableview cell

I've added a button to a tableview cell, but I'm having two problems with it: 我已经在表格单元格中添加了一个按钮,但是我遇到了两个问题:

1) I've invoked a setTarget:action: method on the button, but the action: method never gets called: 1)我已经在按钮上调用了setTarget:action:方法,但是从未调用过action:方法:

[playButton addTarget:self action:@selector(playButtonPressed:) 
                 forControlEvents:UIControlEventTouchUpInside];

2) the cell itself ends up getting selected on the touch, invoking didSelectRowAtIndexPath , which I don't want to happen. 2)单元格本身最终被触摸选中,调用didSelectRowAtIndexPath ,我不想发生这种情况。

I've verified that the button is at least seeing the touch by setting its showsTouchWhenHighlighted property and seeing it "glow" when pressed. 我已经通过设置按钮的showsTouchWhenHighlighted属性并在按下按钮时看到它“发光”,来验证该按钮至少可以看到触摸。 But for whatever reason it looks like the touch event is then getting passed up to its cell superview instead of being handled by the button itself. 但是无论出于何种原因,看起来触摸事件然后都会传递到其单元格超级视图,而不是由按钮本身来处理。

I've tried adding the button directly to the cell's contentView , as well as to other cell subviews, with no effect. 我尝试将按钮直接添加到单元格的contentView以及其他单元格子视图中,没有任何效果。 I've also made sure that the button's superview(s) were all touch-enabled. 我还确保了按钮的超级视图都启用了触摸。

Any thoughts? 有什么想法吗?

Howard 霍华德

-->For your first problem,use this code ->对于第一个问题,请使用此代码

UIButton *imgV1 = [UIButton buttonWithType:UIButtonTypeCustom];
[imgV1 setFrame:CGRectMake(0, 0, 320, 53)];
[imgV1 setBackgroundColor:[UIColor clearColor]]; 
[imgV1 setImage:[UIImage imageNamed:@"expired.png"] forState:UIControlStateNormal];
[imgV1 addTarget:self action:@selector(show_product_details:) forControlEvents:UIControlEventTouchUpInside];

-->For your second problem use this in ->对于第二个问题,请在

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath     {  

[cell setSelectionStyle:UITableViewCellSelectionStyleNone]; [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; } }

There are two ways to do that, the simplest is to add the button to the cell with IB, set a tag number to the button and when you are in the cellForRowAtIndexPath method updating the cell use something like: 有两种方法可以做到这一点,最简单的方法是使用IB将按钮添加到单元格中,为按钮设置标签号,并且当您在cellForRowAtIndexPath方法中更新单元格时,请使用以下方法:

UIButton *myButton = (UIButton *)[cellYouAreUpdating viewWithTag:-1969];

being -1969 the tag number you previously set in IB and cellYouAreUpdating the cell reference. 是-1969您之前在IB和cellYouAreUpdating单元格参考中设置的标签号。 After that you will have a reference to the button in the cell and you could set the add target with the proper selector. 之后,您将引用单元格中的按钮,并且可以使用适当的选择器设置添加目标。

Hope this helps. 希望这可以帮助。

我是您的按钮Y轴或Y轴+高度大于其超级视图(超级视图可能是单元格或单元格的contentview)检查超级视图的高度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM