简体   繁体   中英

Perform action on a button in UITableView

I've a UIButton in UITableViewCell... I want to perform an action on the UIButton..

I need to send data to the @selector method that is registered for this button so that I can perform actions on when the user press this button.

How to accomplish that, though I found that the (id) sender parameter inside the selector function is not always the original button created in cellForRowAtIndexPath function.

Inside the cellForRowAtIndexPath function:

UIImage* pdfImage = [UIImage imageNamed:@"icon_pdf.png"];
UIButton* pdfButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pdfButton setImage:pdfImage forState:UIControlStateNormal];
pdfButton.accessibilityHint = @"path/to/pdf/file";
pdfButton.frame = CGRectMake(0, 0, 40, 40);
[pdfButton addTarget:self action:@selector(openUrlInBrowser:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = pdfButton;

Here's the sender function:

-(void) openUrlInBrowser:(id)sender
{
    NSLog(@"%@", [sender class]);
    NSString * url=[sender accessibilityHint];
    NSLog(@"%@",url);
    NSLog(@"%@",sender);
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}

Hoping I understand correctly the question - I ususally define a tag on the button added in the uitableview which is the index of the row. In cellForRowAtIndexPath :

[button setTag:indexPath.row];

You can then get it back in the target method :

- (void) showdatabases:(id) sender {
int row = [[sender valueForKey:@"tag"] intValue];
...

And query the values in the cell for your processing using :

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];

Alternatively you could get the same result by accessing the superviews of the sender but I find this more difficult to debug.

I prefer to use:

-(void) openUrlInBrowser:(id)sender
{
  UIButton * button = (UIButton *)sender;
  NSString * url=[button.superview accessibilityHint];
  [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}

it not depend on cell position in the table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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