如何使用 PerformSegueForIdentifier

How to use PerformSegueForIdentifier

我刚刚进入 iOS 和 objective-c。我正在学习如何使用 segue,尤其是 unwind segue。

阅读时,我对'shouldPerformSegueForIdentifier'和'performSegueForIdentifier'的用法有点困惑。

我创建了一个包含两个 'ViewControllers'、'ViewController.m' 的示例,如下面的代码所示 'VC_1' 和 'ServiceViewController'

我的问题是:

-我应该何时以及如何使用 'performSegueForIdentifier'

-我应该何时以及如何使用 'shouldIPerformSegueForIdentifier'?

VC_1:

#import "ViewController.h"
#import "ServiceViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
 [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a    
 nib.
 }


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.
}

-(IBAction)btnStartService:(UIButton *)sender {
   if (sender.tag == 1) {
    NSLog(@"CLICKED");

    [self performSegueWithIdentifier:@"seguePassInterval" sender:(id)   
sender];
}
}

-(IBAction)btnExitApp:(UIButton *)sender {
    NSLog(@"EXIT_CLICKED");

}



 - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"seguePassInterval"]) {
    ((ServiceViewController*)segue.destinationViewController).data = @"testData"; //passing data to destinationViewController of type "TestViewController"
    NSLog(@"SEGUE");
}

}


@end

img

prepareForSegue 方法在 segue 执行之前调用,并允许在 ViewController 之间传递数据等等,您可以通过示例检查您的 segue 的标识符是否为 "XxX" 并传递一些数据,或者如果 "YYY" 调用方法

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"seguePassInterval"]) {
    ((TestViewController*)segue.destinationViewController).data = @"testData"; //passing data to destinationViewController of type "TestViewController"
    NSLog(@"SEGUE");
}
}

方法performSegueWithIdentifier是用来用他的标识符执行segue的,需要的时候可以执行segue

最后 shouldPerformSegue 用于避免在您的应用程序处于某种状态时执行 segue,例如,如果您还没有 destinationViewController 数据,您可以 return false 直到你得到那个

希望对您有所帮助