0

我创建了两个页面,分别称为 ViewController 和 SecViewController。在 ViewController 中,这是第一页,有一个按钮和一个标签。我在一个按钮上设置 segue 到 SecViewController,这是第二页。

我正在尝试将 segue 标识符传递到第 2 页,但这并不成功。我测试page1中传入的值,控制台显示

2013-07-05 10:33:54.554 测试2[1314:c07] 1,(空)

这是我的代码:任何人都可以识别我输入错误的代码吗?

视图控制器.h

#import <UIKit/UIKit.h>

@class SecViewController;

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *label;
@property (strong, nonatomic) IBOutlet UIButton *button;

@property (strong, nonatomic) SecViewController *view2;

@end

视图控制器.m

#import "ViewController.h"
#import "SecViewController.h"

@implementation ViewController

@synthesize label, button, view2;

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"1"]){
        view2.received  = [segue identifier];
        NSLog(@"%@, %@", [segue identifier], view2.received);
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [label setText:@"Game Start!"];
}

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

@end

SecViewController.h

#import <UIKit/UIKit.h>

@interface SecViewController : UIViewController

@property (strong, nonatomic) id received;
@property (strong, nonatomic) IBOutlet UILabel *label;

@end

SecViewController.m

#import "SecViewController.h"

@implementation SecViewController

@synthesize label;

- (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.
}

@end
4

1 回答 1

0

您不必为第二个视图控制器创建属性。您可以在 prepareForSegue 中获取它并从第二个视图控制器访问接收到的变量。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"1"]){
        SecViewController *vc  = [segue destinationViewController];
        vc.received = [segue identifier];
        NSLog(@"%@, %@", [segue identifier], vc.received);
    }
}

如果你 nslog 在 secondviewcontroller 中获取收到的值,你会得到什么?

#import "SecViewController.h"

@implementation SecViewController

@synthesize label;

- (void)viewDidLoad
{
    [super viewDidLoad];
NSLog(@"Received %@",self.received);
    // Do any additional setup after loading the view, typically from a nib.
}

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

@end
于 2013-07-05T02:52:41.060 回答