Objective-C程序标题未显示

问题描述

我已在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

谢谢!

解决方法

我正在考虑您不使用情节提要。 就您而言,您必须以编程方式执行所有操作,包括分配导航栏。

- (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";
,

只需说:viewController.title = @“Hello”; https://developer.apple.com/documentation/uikit/uiviewcontroller/1621364-title