在其他类中访问变量

时间:2015-04-15 13:37:31

标签: ios objective-c variables

我有两节课:

classVC: ViewController
classView: UIview

如何从classView中的classVC访问navAndStatusHeight

int navAndStatusHeight = self.navigationController.navigationBar.frame.size.height
                         + [UIApplication sharedApplication].statusBarFrame.size.height;

3 个答案:

答案 0 :(得分:2)

如果是子视图,则在父视图中将高度声明为属性:

@property (nonatomic,strong) NSNumber *navAndStatusHeight;

然后从您的子视图访问此属性。 (我将子视图视为子视图)

如果您不使用segues,可以使用NSUSerDefaults存储int值并将其返回到您需要的任何位置。

存储int:

[[NSUserDefaults standardUserDefaults] setInteger:navAndStatusHeight forKey:@"navHeight"];

要取回它:

NSInteger height = [[NSUserDefaults standardUserDefaults] integerForKey:@"navHeight"];

答案 1 :(得分:0)

从此方法获取最顶层的ViewController

UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

while (topController.presentedViewController) {
    topController = topController.presentedViewController;
}

然后从最顶层的viewcontroller获取导航控制器及其框架。

所以你的代码

int navAndStatusHeight = CGRectGetHeight(topController.navigationController.navigationBar.frame) +
                         CGRectGetHeight([UIApplication sharedApplication].statusBarFrame);

答案 2 :(得分:0)

在classView.h中,将接收变量声明为属性:

@property (nonatomic, assign) NSInteger navAndStatusHeight;

然后在classVC.m中,如果使用storyboard segue,请转到prepareForSegue方法并:

if ([[segue identifier] isEqualToString:@"theSegue"]) {
        classView *cv = [segue destinationViewController];
        [cv setNavAndStatusHeight: yourValue];
}

如果使用xibs,它与推送导航几乎完全相同。

相关问题