简体   繁体   中英

iOS: Loading second view controller without nib file

I have a project, which consists of the standard AppDelegate and ViewController files, but does not utilize nib files.

Here's the code:

delegate header

// AppDelegate.h
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *vc1;
@end

delegate implementation

// AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.vc1 = [[ViewController alloc] init];
    self.window.rootViewController = self.vc1;
    [self.window makeKeyAndVisible];
    return YES;
}
@end

view controller header

//  ViewController.h
#import <UIKit/UIKit.h>

@interface view1 : UIViewController{
    UIButton *button;
}
@end

view controller implementation

//  ViewController.m
#import "ViewController.h"

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect buttonFrame = CGRectMake(30, 30, 100, 30);
    button = [[UIButton alloc] initWithFrame: buttonFrame];
    [button setTitle: @"Switch View" forState: UIControlStateNormal];
    [self.view addSubview: button];

    [button addTarget: self action: @selector(buttonClicked:) forControlEvents: UIControlEventTouchDown];
}

- (void) buttonClicked: (id)sender {
    SecondViewController *vc2 = [[SecondViewController alloc] init];
        //both methods throw the same error - no known class method for selector
    //[self presentViewController:vc2 animated:YES completion:nil];         
    [self presentModalViewController:vc2 animated:YES completion:nil];
}

@end

When trying to load another nib -less view controller (in the buttonClicked method above) , it keeps throwing the error

No known class method for selector 'presentViewController'

What am I doing wrong?

正确的方法如下:

[self presentViewController:vc2 animated: YES completion:nil];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM