UiButton / IBAction - 从一个RootView链接到Storyboard中的mainView

时间:2011-11-17 15:39:42

标签: iphone ios5 storyboard ibaction

我尝试在故事板上调用主ViewController。在我的应用中,还有一个没有xib或情节提要的.h.m文件。

在这个.m文件中,T有一个按钮:

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");

此按钮应链接到Storyboard中的主ViewController。该视图具有标识符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");

}

2 个答案:

答案 0 :(得分:1)

如果您的.m文件未与任何情节提要相关联,则self.storyboard不会Nil

尝试:

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

请务必将storyboardWithName:更改为您的故事板名称。


你可能没有遇到任何错误,因为Objective-C处理nil的方式与其他语言不同,如果你尝试在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"];

答案 1 :(得分: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];