无法在UITableview中的单元格内单击UIButton

时间:2022-06-07 00:19:18

searched already some possible fixes but all did not solve mine.

已经搜索了一些可能的修复,但都没有解决我的问题。

i keep clicking the cell in the uitableview rather than the buttons inside it.

我一直在点击uitableview中的单元格,而不是单击其中的按钮。

here is my code:

这是我的代码:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.backgroundColor = [UIColor blackColor];

    UIView *v  = nil;
    NSArray *array = [cell subviews];

    for (v in array) {
        NSLog(@"%@",[v class]);
        if( [v isKindOfClass:[UIView class]] ){
           [v removeFromSuperview];
        }
    }

    //tb
    if (tableView == self.tb) {

        v = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.tb.bounds.size.width, 120.0)];

        if([feeds count]>0){
            UIImageView *box=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"statusBox.png"]];

            box.userInteractionEnabled = YES;
            [v addSubview:box];

            AsyncImageView *imageView1 = [[AsyncImageView alloc] initWithFrame:CGRectMake(10, 20.0f, 34.0f, 34.0f)];
            imageView1.contentMode = UIViewContentModeScaleAspectFill;
            imageView1.clipsToBounds = YES;

            //cancel loading previous image for cell
            [[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView1];
            if (users1 != nil && users1.imagelink != nil && (id) users1.imagelink !=   [NSNull null]){
               imageView1.imageURL = [NSURL URLWithString:users1.imagelink];
            }
            else{
                imageView1.image=[UIImage imageNamed:@"default_ProfilePic.png"];
            }

            UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myFunction:)];
            tapped.numberOfTapsRequired = 1;
            [imageView1 addGestureRecognizer:tapped];
            [tapped release];

            imageView1.userInteractionEnabled = NO;
            [v addSubview:imageView1];


            UIFont *font     = [UIFont fontWithName:@"TrebuchetMS-Bold" size:11];
            UILabel *descLabel1 = [[UILabel alloc] initWithFrame: CGRectMake(52, 23, 160, 48)];
            descLabel1.text                 = [NSString stringWithFormat:@"%@ %@",users1.userfirstn,users1.userlastn];
            descLabel1.textColor            = [UIColor blackColor];
            descLabel1.font                 = font;
            descLabel1.adjustsFontSizeToFitWidth=YES;
            descLabel1.numberOfLines = 0;
            CGSize expectedLabelSize = [descLabel1.text sizeWithFont:descLabel1.font
                                               constrainedToSize:descLabel1.frame.size
                                                   lineBreakMode:UILineBreakModeWordWrap];

            CGRect newFrame = descLabel1.frame;
            newFrame.size.height = expectedLabelSize.height;
            descLabel1.frame = newFrame;
            descLabel1.numberOfLines = 0;

            descLabel1.userInteractionEnabled = NO;
            [v addSubview:descLabel1];


            UILabel *descLabel2= [[UILabel alloc] initWithFrame: CGRectMake(52, 43, 200, 48)];
            StatusClass *stat1=[feeds objectAtIndex:indexPath.row];
            descLabel2.text                 = [stat1 statcreate];
            descLabel2.textColor            = [UIColor blackColor];
            descLabel2.font                 = font;
            descLabel2.adjustsFontSizeToFitWidth=YES;
            descLabel2.numberOfLines = 0;
            CGSize expectedLabelSize2 = [descLabel2.text sizeWithFont:descLabel2.font
                                                constrainedToSize:descLabel2.frame.size
                                                    lineBreakMode:UILineBreakModeWordWrap];

            CGRect newFrame2 = descLabel2.frame;
            newFrame2.size.height = expectedLabelSize2.height;
            descLabel2.frame = newFrame2;
            descLabel2.numberOfLines = 0;

            descLabel2.userInteractionEnabled = NO;
            [v addSubview:descLabel2];

            UILabel *descLabel3= [[UILabel alloc] initWithFrame: CGRectMake(10, 63, 280, 80)];
            StatusClass *stat=[feeds objectAtIndex:indexPath.row];
            descLabel3.text                 = [stat stattext];
            descLabel3.textColor            = [UIColor blackColor];
            descLabel3.font                 = font;
            descLabel3.adjustsFontSizeToFitWidth=YES;
            descLabel3.numberOfLines = 0;

            descLabel3.userInteractionEnabled = NO;
            [v addSubview:descLabel3];

            //comment button
            UIButton *buttonC = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [buttonC addTarget:self action:@selector(sendComment:) forControlEvents:UIControlEventTouchUpInside];
            [buttonC setImage:[UIImage imageNamed:@"comment.png"] forState:UIControlStateNormal];
            buttonC.frame = CGRectMake(2, 160, 145, 35);

            buttonC.userInteractionEnabled = YES;
            [v addSubview:buttonC];

            //share button
            UIButton *buttonS = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            buttonS.tag = indexPath.row;
            [buttonS addTarget:self action:@selector(sendShare:) forControlEvents:UIControlEventTouchUpInside];
            [buttonS setImage:[UIImage imageNamed:@"share.png"] forState:UIControlStateNormal];
            buttonS.frame = CGRectMake(150, 160, 140, 35);

            buttonS.userInteractionEnabled = YES;
            [v addSubview:buttonS];

        }
        v.userInteractionEnabled = YES;
        [cell addSubview:v];
    }
    return cell; 
}

I also tried the UITapGestureRecognizer for the buttons and still not working.

我也尝试了按钮的UITapGestureRecognizer,但仍无法正常工作。

Thanks.

谢谢。

9 个解决方案

#1


22  

I'm just baffled by this issue....

我对此问题感到困惑....

I managed to fix this problem by doing this on one project:

我设法通过在一个项目上执行此操作来解决此问题:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("RegCell", forIndexPath: indexPath) as! CustomCell

    cell.contentView.userInteractionEnabled = false // <<-- the solution

    return cell
}

but the same did not work for a different project. I have no idea why...

但同样不适用于不同的项目。我不知道为什么...

#2


19  

There is another potential cause of problems like this one, and that is UITableViewCells now have a contentView. This can and will be placed in front of other views in your custom table view cells in order to pick up touches and detect cell selection. In doing so, it may block touches to any views behind it. I've especially noticed this annoyance when creating cells using nibs.

还有另一个潜在的问题,比如这个问题,那就是UITableViewCells现在有一个contentView。这可以并且将被放置在自定义表格视图单元格中的其他视图之前,以便拾取触摸并检测单元格选择。这样做可能会阻止其后面的任何视图的触摸。我在使用笔尖创建单元格时特别注意到这种烦恼。

The accepted means for dealing with this is to ensure that all subviews are added not to the tableview cell itself, but to its contentView. This is a read-only property that adjusts its own frame under certain circumstances, for example when slid sideways to reveal the delete button, or during editing mode. You should therefore ensure that any items you do add to the contentVieware intelligently sized and have the correct resizing behaviour.

处理此问题的可接受方法是确保所有子视图不是添加到tableview单元本身,而是添加到其contentView。这是一个只读属性,可在某些情况下调整自己的帧,例如,当侧向滑动以显示删除按钮时,或在编辑模式期间。因此,您应确保您添加到contentView的任何项目都具有智能大小并具有正确的大小调整行为。

Also be aware that by adding cells to the contentView, you may yourself block touches to it and thus prevent the cell from being selected. I personally try not to allow cell selection in tableviews containing cells with custom user-enabled controls. It only leads to confusion and awkward interfaces. In fact, I'm seriously considering replacing all UITableViews in my future projects with UICollectionViews, which are far more adaptable.

另外请注意,通过向contentView添加单元格,您可以自己阻止对它的触摸,从而防止选择单元格。我个人尝试不允许在包含具有自定义用户启用控件的单元格的tableviews中选择单元格。它只会导致混乱和尴尬的界面。事实上,我正在认真考虑用UICollectionViews替换我未来项目中的所有UITableViews,它们的适应性更强。

-Ash

-灰

#3


4  

Your UIButton='s y offset is given as 160 and UIView's height is just given as 120. Please change the UIButton's y offset and try.

你的UIButton =的y偏移量为160,UIView的高度仅为120.请更改UIButton的y偏移量并尝试。

#4


4  

For Swift 3 and Storyboard

对于Swift 3和Storyboard

For me, I had to enable multiple touch inside the content view, and enable user interaction on everything - the table view, table view cell, content view, and UIButton. I was using storyboard.

对我来说,我必须在内容视图中启用多点触摸,并在所有内容上启用用户交互 - 表视图,表视图单元格,内容视图和UIButton。我在使用故事板。

I also set up my tableview cell as a subclass.

我还将tableview单元格设置为子类。

Since I couldn't find an answer here when I was exploring the problem, I posted another question on stack overflow about this. You can see my code and download a project with this working here: Can't click button inside UITableViewCell?

由于我在探索问题时无法在这里找到答案,因此我发布了有关此问题的堆栈溢出的另一个问题。您可以在此处查看我的代码并下载项目:无法单击UITableViewCell内的按钮?

#5


3  

The UITableViewCell is handling all the gestures by default. Set cell.selectionStyle = UITableViewCellSelectionStyleNone; to make it disable the default behaviour.

UITableViewCell默认处理所有手势。设置cell.selectionStyle = UITableViewCellSelectionStyleNone;使其禁用默认行为。

#6


2  

I ran into this problem, but in my case it was not related to the table view, instead it was because I was using subviews in my button for which userInteractionEnabled was true, setting that value for false (NO) for all the button's subviews fixed the issue for me.

我遇到了这个问题,但在我的情况下,它与表视图无关,而是因为我在我的按钮中使用了userInteractionEnabled为true的子视图,为所有按钮的子视图修复了该值为false(NO)这个问题对我而言。

#7


0  

Create a custom UITableViewCell. Refer this link.

创建自定义UITableViewCell。请参阅此链接。

Say you have a UIButton by the name of displayButton, you can do something like this:

假设你有一个名为displayButton的UIButton,你可以这样做:

Inside your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath, after you create your cell,

在你的 - (UITableViewCell *)tableView :( UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中创建你的单元格后,

[cell.dislayButton addTarget: self
                             action: @selector(replyButtonPressed:withEvent:)
                   forControlEvents: UIControlEventTouchUpInside];

And the create the method like so in your ViewController:

并在ViewController中创建如此方法:

- (void) replyButtonPressed: (id) sender withEvent: (UIEvent *) event
{
    UITouch * touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView: self.tableView];
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];
}

#8


0  

I have the same issue, and somehow I figured out my mistake.
After I changed the constraints with self(UITableViewCell) to constraints with contentView of self(UITableViewCell),my cell's button is clickable again.

我有同样的问题,不知怎的,我弄清楚了我的错误。在我使用self(UITableViewCell)将约束更改为具有contentView of self(UITableViewCell)的约束后,我的单元格按钮可再次单击。

#9


0  

I was doing this:

我这样做:

let plusButton: UIButton = {
        let v = UIButton()
        v.setImage(plusImg, for: .normal)
        v.tintColor = .dark
        v.translatesAutoresizingMaskIntoConstraints = false
        v.addTarget(self, action: #selector(plusButtonHandler), for: .touchUpInside)
        // adding targets here did not work
        return v
    }()

And it appears invoking the addTarget method inside of the closure did not work. When I factored the addTarget method out and instead put it in the initializer, everything worked!

而且似乎在闭包内调用addTarget方法不起作用。当我将addTarget方法考虑在内并将其放入初始化器中时,一切正常!

#1


22  

I'm just baffled by this issue....

我对此问题感到困惑....

I managed to fix this problem by doing this on one project:

我设法通过在一个项目上执行此操作来解决此问题:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("RegCell", forIndexPath: indexPath) as! CustomCell

    cell.contentView.userInteractionEnabled = false // <<-- the solution

    return cell
}

but the same did not work for a different project. I have no idea why...

但同样不适用于不同的项目。我不知道为什么...

#2


19  

There is another potential cause of problems like this one, and that is UITableViewCells now have a contentView. This can and will be placed in front of other views in your custom table view cells in order to pick up touches and detect cell selection. In doing so, it may block touches to any views behind it. I've especially noticed this annoyance when creating cells using nibs.

还有另一个潜在的问题,比如这个问题,那就是UITableViewCells现在有一个contentView。这可以并且将被放置在自定义表格视图单元格中的其他视图之前,以便拾取触摸并检测单元格选择。这样做可能会阻止其后面的任何视图的触摸。我在使用笔尖创建单元格时特别注意到这种烦恼。

The accepted means for dealing with this is to ensure that all subviews are added not to the tableview cell itself, but to its contentView. This is a read-only property that adjusts its own frame under certain circumstances, for example when slid sideways to reveal the delete button, or during editing mode. You should therefore ensure that any items you do add to the contentVieware intelligently sized and have the correct resizing behaviour.

处理此问题的可接受方法是确保所有子视图不是添加到tableview单元本身,而是添加到其contentView。这是一个只读属性,可在某些情况下调整自己的帧,例如,当侧向滑动以显示删除按钮时,或在编辑模式期间。因此,您应确保您添加到contentView的任何项目都具有智能大小并具有正确的大小调整行为。

Also be aware that by adding cells to the contentView, you may yourself block touches to it and thus prevent the cell from being selected. I personally try not to allow cell selection in tableviews containing cells with custom user-enabled controls. It only leads to confusion and awkward interfaces. In fact, I'm seriously considering replacing all UITableViews in my future projects with UICollectionViews, which are far more adaptable.

另外请注意,通过向contentView添加单元格,您可以自己阻止对它的触摸,从而防止选择单元格。我个人尝试不允许在包含具有自定义用户启用控件的单元格的tableviews中选择单元格。它只会导致混乱和尴尬的界面。事实上,我正在认真考虑用UICollectionViews替换我未来项目中的所有UITableViews,它们的适应性更强。

-Ash

-灰

#3


4  

Your UIButton='s y offset is given as 160 and UIView's height is just given as 120. Please change the UIButton's y offset and try.

你的UIButton =的y偏移量为160,UIView的高度仅为120.请更改UIButton的y偏移量并尝试。

#4


4  

For Swift 3 and Storyboard

对于Swift 3和Storyboard

For me, I had to enable multiple touch inside the content view, and enable user interaction on everything - the table view, table view cell, content view, and UIButton. I was using storyboard.

对我来说,我必须在内容视图中启用多点触摸,并在所有内容上启用用户交互 - 表视图,表视图单元格,内容视图和UIButton。我在使用故事板。

I also set up my tableview cell as a subclass.

我还将tableview单元格设置为子类。

Since I couldn't find an answer here when I was exploring the problem, I posted another question on stack overflow about this. You can see my code and download a project with this working here: Can't click button inside UITableViewCell?

由于我在探索问题时无法在这里找到答案,因此我发布了有关此问题的堆栈溢出的另一个问题。您可以在此处查看我的代码并下载项目:无法单击UITableViewCell内的按钮?

#5


3  

The UITableViewCell is handling all the gestures by default. Set cell.selectionStyle = UITableViewCellSelectionStyleNone; to make it disable the default behaviour.

UITableViewCell默认处理所有手势。设置cell.selectionStyle = UITableViewCellSelectionStyleNone;使其禁用默认行为。

#6


2  

I ran into this problem, but in my case it was not related to the table view, instead it was because I was using subviews in my button for which userInteractionEnabled was true, setting that value for false (NO) for all the button's subviews fixed the issue for me.

我遇到了这个问题,但在我的情况下,它与表视图无关,而是因为我在我的按钮中使用了userInteractionEnabled为true的子视图,为所有按钮的子视图修复了该值为false(NO)这个问题对我而言。

#7


0  

Create a custom UITableViewCell. Refer this link.

创建自定义UITableViewCell。请参阅此链接。

Say you have a UIButton by the name of displayButton, you can do something like this:

假设你有一个名为displayButton的UIButton,你可以这样做:

Inside your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath, after you create your cell,

在你的 - (UITableViewCell *)tableView :( UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中创建你的单元格后,

[cell.dislayButton addTarget: self
                             action: @selector(replyButtonPressed:withEvent:)
                   forControlEvents: UIControlEventTouchUpInside];

And the create the method like so in your ViewController:

并在ViewController中创建如此方法:

- (void) replyButtonPressed: (id) sender withEvent: (UIEvent *) event
{
    UITouch * touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView: self.tableView];
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];
}

#8


0  

I have the same issue, and somehow I figured out my mistake.
After I changed the constraints with self(UITableViewCell) to constraints with contentView of self(UITableViewCell),my cell's button is clickable again.

我有同样的问题,不知怎的,我弄清楚了我的错误。在我使用self(UITableViewCell)将约束更改为具有contentView of self(UITableViewCell)的约束后,我的单元格按钮可再次单击。

#9


0  

I was doing this:

我这样做:

let plusButton: UIButton = {
        let v = UIButton()
        v.setImage(plusImg, for: .normal)
        v.tintColor = .dark
        v.translatesAutoresizingMaskIntoConstraints = false
        v.addTarget(self, action: #selector(plusButtonHandler), for: .touchUpInside)
        // adding targets here did not work
        return v
    }()

And it appears invoking the addTarget method inside of the closure did not work. When I factored the addTarget method out and instead put it in the initializer, everything worked!

而且似乎在闭包内调用addTarget方法不起作用。当我将addTarget方法考虑在内并将其放入初始化器中时,一切正常!