How to create navigationController programmatically

Hi developers,

I created a new project like this : iOS / App / Storyboard / Objective-C. Added an UITableView inside the default named ViewController class. Objective-C is 100% compatible with C, it's great!

When I click on a table cell, I wanted to navigate to another view of View2 class. But the navigationController is nil inside the tableView:didSelectRowAtIndexPath: method. I had to do it through the Xcode UI: " Editor / Embed in / Navigation Controller ", this worked.

But my question is: How can I create navigationController programmatically? I don't want to do it with Storyboard because sometimes I delete some UI elements some files still keep the deleted elements.

I read some posts and some said, create instance of "ViewController" in AppDelegate.m in application: didFinishLaunchingWithOptions . Isn't the default name "ViewController" created automatically by the procedure? How can I interrupt this procedure?

Thanks!


- (void)tableView:(UITableView *)tableView 
        didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    View2 *view = [[View2 alloc] init];
    view.text = self.mutArray[indexPath.row];

    // navigationController is nil
    [self.navigationController pushViewController:view 
        animated:YES];

}

Xcode: Version 13.1 (13A1030d), macOS: 12.0.1 (21A559)

You will find details here:

https://stackoverflow.com/questions/21609921/how-to-add-navigation-controller-programmatically/36203448

.

I don't want to do it with Storyboard

It is much easier to do it in storyboard !

sometimes I delete some UI elements some files still keep the deleted elements

Probably because you do not delete in the right way. And you should also do a Clean Build Folder after deleting.

I hope this can help future me. In Xcode 13.1, add the following code in SceneDelegate.m.

// Refer: https://blog.csdn.net/Alingjiu/article/details/79828365


//  SceneDelegate.m
#import "ViewController.h" //add this header
//...

- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    ViewController *viewController = [[ViewController alloc] init];
    UINavigationController *navigationController =
        [[UINavigationController alloc] initWithRootViewController:viewController];
    self.window.rootViewController = navigationController;
}

How to create navigationController programmatically
 
 
Q