2011-11-17 45 views
1

我尝试在故事板上调用主要的ViewController。在我的应用程序中,还有一个额外的.h,.m文件,没有xib或storyboard。UiButton/IBAction - 从RootView到故事板中的mainView的链接

在这个.m文件牛逼craeted一个按钮:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button addTarget:self action:@selector(home:)forControlEvents:UIControlEventTouchDown]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
[self.view addSubview:button]; 
NSLog(@"Home-Button line 645"); 

这个按钮应该链接到我的故事板主视图控制器。该视图具有标识符HauptMenu。我没有错误,但视图不会改变到我的主ViewController。哪里不对?

- (IBAction)home:(id)sender { 
    NSLog(@"Button was tapped"); 
    ViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"HauptMenu"]; 

    NSLog(@"1"); 
    [viewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal]; 
    NSLog(@"2"); 
    [self.navigationController pushViewController:viewController animated:NO]; 
    [viewController release]; 
    NSLog(@"3"); 

} 

回答

1

如果.m文件不与任何故事板相关,不会self.storyboardNil

尝试:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName: 
           @"MainStoryboard" bundle:[NSBundle mainBundle]]; 
ViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"HauptMenu"]; 

确保将storyboardWithName:改变无论你的故事板而得名。


因为Objective-C的比其他语言处理无不同,您可能不会得到任何错误,它(通常)不会,如果你试图对nil调用的方法抛出一个异常,它只会返回nil 。下面的代码会很乐意跑,投掷没有编译或运行时错误:

UIViewController * test = nil; 
[test viewDidLoad]; 

NSString * storyBoardName; 
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { 
    storyBoardName = @"MainStoryboard_iPad"; 
} else { 
    storyBoardName = @"MainStoryboard_iPhone"; 
} 
UIStoryboard *storyboard = [UIStoryboard storyboardWithName: 
            storyBoardName bundle:[NSBundle mainBundle]]; 
ViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"HauptMenu"]; 
+0

谢谢!!!!!我拥有它! – webschnecke

+0

但有一个问题更多;-)我使用MainStoryboard_iphone和MainStoryboard_ipad。我只想使用一个.h和.m文件。这是可以改变的,或者我该怎么做? – webschnecke

+0

查看我的编辑 – Kevin

0

我有这个问题我自己。现在感谢这个答案,它的工作原理!

这里是我的代码,希望其他人可以使用此:

// Declare the storyboard 
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]]; 

// Declare the next view controller 
NextViewController *nextViewController = [storyboard instantiateViewControllerWithIdentifier:@"NextViewController"]; 

// Pass value 
nextViewController.result = result; 
[currentObject memberfunction:value]; 

// Define transition 
nextViewController.modalTransitionStyle=UIModalTransitionStyleCoverVertical; 

// Perform change 
[self presentModalViewController:nextViewController animated:YES];