Using Subclassed UIViewController

I'm trying to subclass UIViewController. And I've written the following.

import UIKit

class BaseViewController: UIViewController {
	let titleText: String
	
	init(titleText: String) {
		self.titleText = titleText
		super.init(nibName: nil, bundle: nil)
	}
	
	required init?(coder aDecoder: NSCoder) {
		self.titleText = ""
		super.init(coder: aDecoder)
		setup()
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
	}
	
	
	// MARK: - Setup
	func setup() {
		print("GGG: \(titleText)")
		let navBar = navigationController!.navigationBar
		navBar.barTintColor = UIColor.yellow
		let atext = NSMutableAttributedString(string: titleText)
		atext.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black, range: NSMakeRange(0, atext.length))
		atext.addAttribute(NSAttributedString.Key.strokeColor, value: UIColor.gray, range: NSMakeRange(0, atext.length))
		atext.addAttribute(NSAttributedString.Key.strokeWidth, value: NSNumber.init(value: -1.0), range: NSMakeRange(0, atext.length))
		let titleLabel: UILabel = UILabel(frame: CGRect(origin: CGPoint(x: 15.0, y: 0), size: CGSize(width: 320.0 - 120.0, height: 44.0)))
		titleLabel.attributedText = atext
		titleLabel.textAlignment = NSTextAlignment.center
		titleLabel.font = UIFont(name: "Helvetica", size: 24.0)
		self.navigationItem.titleView = titleLabel
	}
}

And I subclass it with a view controller named HomeViewController as follows.

import UIKit

class HomeViewController: BaseViewController {
	override init(titleText: String) {
		super.init(titleText: "Jim")
	}
	
	required init?(coder aDecoder: NSCoder) {
		super.init(coder: aDecoder)
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
	}
}


But the setup method in BaseViewController never gets the titleText variable ("Jim") from HomeViewController. What am I doing wrong?

Thanks.

I tested and called as:

let homeVC = HomeViewController(titleText: "HELLO")
print(homeVC.titleText)

print is Jim.

But if you call from a segue, or nav, loading from storyboard, init is not called:

To check:

     override init(titleText: String) {
          super.init(titleText: "Jim")
          print("I called init")
     }

"I called init" is not printed.

So, you have to set it in viewDidLoad

     override func viewDidLoad() {
          super.viewDidLoad()
          self.titleText = "Jim"
     }

and change titleText as var in BaseViewController

It looks like you are missing a call to setup() in init(titleText:) of the base class, so you never call setup when you initialize that way.

View controllers loaded from storyboards are initialized using the designated initializer

init(nibName nibNameOrNil: String?,  bundle nibBundleOrNil: Bundle?)

Try overriding this initializer instead.

Using Subclassed UIViewController
 
 
Q