iOS:加载没有 nib 文件的第二个 View Controller

标签 ios objective-c uiviewcontroller uikit xib

我有一个项目,它由标准的 AppDelegateViewController 文件组成,但不使用 nib 文件。

代码如下:

委托(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)实现

// 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

查看 Controller header

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

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

View Controller 实现

//  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

当尝试加载另一个 nib-less view controller (在上面的 buttonClicked 方法中) 时,它不断抛出错误

No known class method for selector 'presentViewController'

我做错了什么?

最佳答案

正确的方法如下:

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

关于iOS:加载没有 nib 文件的第二个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286203/

相关文章:

ios - 如何使用身份验证方法快速访问 Laravel API?

ios - 触摸屏幕/控件时移动

ios - UIViewController 上的自定义属性,如 splitViewController 或 tabBarController

ios - 从自定义容器 Controller 观察 subview Controller 的工具栏项

ios - 将 View Controller 插入导航 Controller 后,不会触发 viewDidLoad(和 loadView)

ios - UINavigationController barstyle 属性改变布局

iOS 应用程序在 map 缩小到最大值时关闭

ios - 将按钮限制为 UIImageView 内的图像

iphone - 如何在 iOS 应用程序中嵌入 Flash 文件

ios - 在 Interface Builder 中添加约束时 Xcode 无限期挂起