Reputation: 109
I'm trying to understand the life cycle of view controllers. I need to use TabBar to switch controllers. And when switching controllers, I need the label to display life-cycle methods, not only of the controller on which I now find, but also from others.
I created an empty array private var arrayOfMethods = [String]()
in which I add a triggered method every time.
class ViewController: UIViewController {
private var arrayOfMethods = [String]()
@IBOutlet var greenLabel: UILabel!
@IBOutlet var blueLabel: UILabel!
@IBOutlet var yellowLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
printMessage()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
printMessage()
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
printMessage()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
printMessage()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
printMessage()
}
func printMessage(line: Int = #line, function: String = #function) {
print("\(title ?? "nil"). Line: \(line) of function \(function)")
arrayOfMethods.append(function)
let string = arrayOfMethods.joined(separator: "\n")
greenLabel.text = "\(title ?? "nil") \(string)"
}
}
Upvotes: 0
Views: 60
Reputation: 15778
You can create a common class and call its function from all of your view controllers
class Helper: NSObject {
private var arrayOfMethods = [String]()
static let shared = Helper()
let mainLabel = UITextView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))
private override init() {
super.init()
}
func printMessage(vc: UIViewController, line: Int = #line, function: String = #function) {
print("\(vc.title ?? "nil"). Line: \(line) of function \(function)")
arrayOfMethods.append( (vc.title ?? "nil") + "-" + function)
let string = arrayOfMethods.joined(separator: "\n")
guard let window = UIApplication.shared.keyWindow else { return }
if !window.subviews.contains(mainLabel) {
window.addSubview(mainLabel)
window.bringSubviewToFront(mainLabel)
}
mainLabel.text = string
}
}
And call this singleton class method from all your view controllers like this
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Helper.shared.printMessage(vc: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Helper.shared.printMessage(vc: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Helper.shared.printMessage(vc: self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Helper.shared.printMessage(vc: self)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Helper.shared.printMessage(vc: self)
}
}
Output
Upvotes: 1