Perform a Segue Called by a UITableViewCell

2019-05-10 11:19发布

问题:

I have some UIButtons in a custom table view cell that when pressed I want them to call segues in the view controller that is host to the table view that the cells are in. What I am doing now is declaring an action like this: - (void)action;

in the class that the table view is in. And then I am calling that action from the cell like this:

ViewController *viewController = [[ViewController alloc] init];
[viewController action];

However when the action is called it says that there is no such segue for the view controller which I know to be incorrect. Calling "action" from the view controller itself works perfectly, just not from the cell.

Also, here is the code to perform the segue:

-(void)action {
     [self performSegueWithIdentifier:@"action" sender:self];
}

How can I make this work?

Any suggestions are appreciated.

UPDATE:

I just tried to set a delegate on the cell like this:

Cell's header file: @class PostCellView;

@protocol PostCellViewDelegate
-(void)action;
@end

@interface PostCellView : UITableViewCell <UIAlertViewDelegate, UIGestureRecognizerDelegate>

@property (weak, nonatomic) id <PostCellViewDelegate> delegate;

And in the main file for the cell I call the action like this: [self.delegate action];

and in the header for the view that hosts the Table View I import the cell like this: #import "PostCellView.h"

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, PostCellViewDelegate>

Then in the main file for that view I have the cells action:

-(void)action {

    [self performSegueWithIdentifier:@"action" sender:self];

}

But the action is never performed, I checked. I logged when I call the action from the cell and I put an NSLog on the action itself and the log for calling it from the cell worked but not the action.

回答1:

I think your problem is with this ViewController *viewController = [[ViewController alloc] init]; [viewController action]; You are initiating a new ViewController and not getting the current one the cell is in.

Maybe you can set a delegate on the cell so the cell has a reference to the viewController



回答2:

The simple approach to create a button and call its handler programatically is

UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(100, 100, 80, 40)];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:button]; //self.view is the view on which you want to add button

and its handler should be defined like this in your implementation file:

-(void)buttonClick:(id)sender{
    NSLog(@"button clicked");
    // your code on click of button 
}

You can check iOS documentation.

Hope this will help you to find out your problem. :)