如何访问不同视图控制器中的属性?

时间:2015-01-21 23:36:50

标签: ios storyboard

我有两个故事板,每个故事板都有自己的视图控制器,但我需要根据第一个视图控制器中按下的按钮更改第二个故事板的外观。

在第一个视图控制器中,我有:

// First view controller .h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"

@interface FirstViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIButton *LevelOneButton; // tag 0
@property (strong, nonatomic) IBOutlet UIButton *LevelTwoButton; // tag 1

-(IBAction)selectLevel:(UIButton *)sender; // both buttons connected to this method
@property (assign, nonatomic) int levelSelect;

@end

然后在第一个.m文件中:

//FirstViewController.m
-(IBAction)selectLevel:(UIButton *)sender {
    if (sender.tag == 0) {
        _levelSelect = 0;
    }
    if (sender.tag == 1) {
        _levelSelect = 1;
    }
}

此代码工作正常但问题出现在我拥有的secondViewController中。当我尝试访问SecondViewController中的levelSelect属性时,我得到错误“Property'levelSelect'找不到'FirstViewController'类型的对象”或“Unexpected identifier levelSelect”或这些行中的某些内容。我已经尝试了我能想到的每一件事以及我在StackOverflow上发现的与此相关的每个问题,但没有一个能解决问题。谁知道我做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该在第二个视图控制器上设置属性,因为您正在推动或进行推送。

所以在你的第一个视图控制器中它看起来应该是这样的:

#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIButton *levelOne;
@property (strong, nonatomic) IBOutlet UIButton *levelTwo;
@property (assign, nonatomic) int selectedLevel;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.levelOne.tag = 1;
    self.levelTwo.tag = 2;
}

- (IBAction)selectLevel:(UIButton *)sender
{
    if (sender.tag == 1) {
        self.selectedLevel = 1;
    } else {
        self.selectedLevel = 2;
    }

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

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    SecondViewController *dest = segue.destinationViewController;
    dest.levelSelect = self.selectedLevel;
}

@end

现在,当viewDidLoadSecondViewController上调用该属性时,您可以使用它。像这样:

#import "SecondViewController.h"

@interface SecondViewController ()
@property (strong, nonatomic) IBOutlet UILabel *levelLabel;

@end

@implementation SecondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.levelLabel.text = [@(self.levelSelect) stringValue];

}

@end

快速编辑,如果你不使用segues,你可以通过手动推送来做同样的事情。看起来像是:

- (IBAction)selectLevel:(UIButton *)sender
{
    if (sender.tag == 1) {
        self.selectedLevel = 1;
    } else {
        self.selectedLevel = 2;
    }

    SecondViewController *secondVC = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"second"];
    secondVC.levelSelect = self.selectedLevel;
    [self.navigationController pushViewController:secondVC animated:YES];
}