ios Objective-C Programmatic title not showing

kxeu7u2r  于 2023-05-19  发布在  iOS
关注(0)|答案(2)|浏览(191)

我在ViewController.m中设置了self.navigationItem.title = @"Hello";,但它不显示:
AppDelegate.m

#import "AppDelegate.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    
    ViewController *viewController = [[ViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
    
    self.window.rootViewController = navController;
    [self.window makeKeyAndVisible];
    
    return YES;
}

#pragma mark - UISceneSession lifecycle

- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options  API_AVAILABLE(ios(13.0)) {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}

- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions  API_AVAILABLE(ios(13.0)) {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

@end

ViewController.m

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

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"Hello";
    self.view.backgroundColor = [UIColor systemBlueColor];
}

@end
nqwrtyyt

nqwrtyyt2#

我在考虑你没有使用故事板。在您的例子中,您必须以编程方式完成所有工作,包括分配导航栏。

- (void)viewDidLoad {
    [super viewDidLoad];
    UINavigationBar *navbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
    UINavigationItem *title = [[UINavigationItem alloc] initWithTitle:@"Hello"];
    
     self.view.backgroundColor = [UIColor systemBlueColor];
    [navbar setItems:@[title]];
    [self.view addSubview:navbar];
}

如果您使用的是故事板,这个简单的命令就可以工作,而不需要appDelegate中的任何东西。

self.navigationItem.title = @"Hello";

相关问题