Custom UITableViewCell and IBAction

我是研究僧i 提交于 2019-11-29 00:39:39

Ok, finally I got the answer, looking into different forums, people were suggesting to do something like this

in the custom table view controller in cellForRowAtIndexPath do this

cell.addToCart.tag = indexPath.row;
[cell.addToCart addTarget:self action:@selector(addToCart:)    
                               forControlEvents:UIControlEventTouchUpInside];

where addToCart is name of UIButton in my customUITableViewCell. It didn't seems to work for me. So this is what I did

-(IBAction) addToCart:(id) sender{
        NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)
                    [[sender superview] superview]];
    NSLog(@"The row id is %d",  indexPath.row); 
 }

And then through interfacebuilder I associated the action of my button to addToCart IBAction on my table view controller.

Much less hackerific.

[cell.button1 addTarget:self action:@selector(addToCart:event:) forControlEvents:UIControlEventTouchUpInside];


- (void)addToCart:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];

}
George Sachpatzidis

The accepted answer does not work any more. Please refer to this post

It does it that way:

- (void)checkButtonTapped:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
     ...
    }
}

Many of the developer used custom view to show custom cell on Table view for older version of iOS. If you are one of them, then you will have to face a problem that your button click action will no longer work with iOS7.

How to resolve this:

You have two options:

Option 1: Create the new lay out with new table cell instead of taking view. and put all layouts again in table cell.

I know, this will require a lot of effort.If you don't want to do this, we have a very small hack for it:option 2

Option 2: Create a IBOutlet for your button and add this button as a subview of your cell's content view.

[self.myCell.contentView addSubview:self.btn_click];

The above line of code will add btn_click as a subview of you content view. Now button click action should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!