UIButton selector method with parameters or define the selector method on button creation

224 views Asked by At

I have a table in which each row object can have an specific content (text, text with URL - the result is to open the link in Safari - and images).

What I do is I create a view for each detail, but for example for the text with URL, I create a button with a selector method and I don't have the chance to set the URL parameter for that selector - it always displays the last URL created.

Is there any way to have the code that opens the link on the button creation? (There I have the correct values.)

1

There are 1 answers

1
Meriw On

Use the UIButton *sender parameter in your selector method to locate the row associated with the button tapped and then get the associated URL to the item.

Your selector method should look something like this:

- (void)didTapLinkButtonInCell:(UIButton *)sender {
     CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
     NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];

     // If you have the items of your table in an array named 'items', for example
     NSLog("Clicked URL is %@". self.items[indexPath.row].url);
}

You can also use [cellForRowAtIndexPath:indexPath] if you need to access the cell where the button was pressed.