Note: My previous answer was using Storyboard. But since the questioner didn't want to use storyboard, I replace my answer without using storyboard.
[ this answer was inspired by https://stackoverflow.com/a/41095757/3549695 ]
First, delete the Main.storyboard. Then in Project -> Deployment Info -> Main Interface (pick LaunchScreen instead of 'Main')
Then on AppDelegate.swift modify didFinishLaunching with the following:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let discoverVC = DiscoverVC() as UIViewController
let navigationController = UINavigationController(rootViewController: discoverVC)
navigationController.navigationBar.isTranslucent = false
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
The DiscoverVC.swift looks like this:
import UIKit
class DiscoverVC: UIViewController, SetLocationDelegate {
var name = ""
// to instantiate LocationVC once only for testing
var notVisted = true
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .yellow
loadLocationVCOnlyOnce()
}
func loadLocationVCOnlyOnce() {
// only visit one
guard notVisted else { return }
let locationVC = LocationVC()
locationVC.delegate = self
self.navigationController?.pushViewController(locationVC, animated: true)
}
func getLocation(loc: String) {
self.name = loc
print(name)
}
}
And the LocationVC looks like this:
import UIKit
protocol SetLocationDelegate: class {
func getLocation(loc: String)
}
class LocationVC: UIViewController {
weak var delegate: SetLocationDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .cyan
self.delegate?.getLocation(loc: "Sam")
}
}
When you start it will automatically move from DiscoverVC (yellow background) to LocationVC (cyan background).
Then after you click the 'Back' button on top, you will see the 'Sam' printed in your console. And your view returned to DiscoverVC (yellow background).