无法使用方法刷新来打印当前的ViewController名称

时间:2019-09-25 14:22:14

标签: ios swift

我要打印7 6 18 5 20 48 2 97 8 3 6 9 12 28 5 7 10 名称,除了使用每个ViewController扩展名之外,还可以使用ViewController扩展名打印ViewController名称吗?或有什么建议?。

例如,如果您处于登录页面,则应打印ViewController,如果移至主屏幕,则应打印LoginViewController,我尝试了以下代码,但未打印确切的班级名称。

HomeViewController

extension UIViewController { @objc dynamic func _tracked_viewWillAppear(_ animated: Bool) { print("ClassName@: "+String(describing: type(of: self))) _tracked_viewWillAppear(animated) } static func swizzle() { if self != UIViewController.self { return } let _: () = { let originalSelector = #selector(UIViewController.viewWillAppear(_:)) let swizzledSelector = #selector(UIViewController._tracked_viewWillAppear(_:)) let originalMethod = class_getInstanceMethod(self, originalSelector) let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) method_exchangeImplementations(originalMethod!, swizzledMethod!); }() } 文件中

Appdelegate.swift

输出:-

func application( _ application: UIApplication, 
            didFinishLaunchingWithOptions 
            launchOptions: [UIApplication.LaunchOptionsKey: Any]?
            ) -> Bool {

               UIViewController.swizzle()

             return true
}

但是它不是打印名称ClassName@: UIInputWindowController ClassName@: UISystemKeyboardDockController ClassName@: UICompatibilityInputViewController ClassName@: UICompatibilityInputViewController ClassName@: UICompatibilityInputViewController ClassName@: UICompatibilityInputViewController ClassName@: UICompatibilityInputViewController ClassName@: UISystemKeyboardDockController 。 谢谢。

3 个答案:

答案 0 :(得分:1)

我会做类似的事情

struct StringUtils {
    static func className(_ obj: AnyObject) -> String {
        return String(describing: type(of: obj))
    }
}

然后将其命名为

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        print(StringUtils.className(self))
    }

}

答案 1 :(得分:0)

您可以使用type(of: T)方法

print(type(of: self))

游乐场示例:

import UIKit

class SomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print(type(of: self))
    }
}

let vc = SomeViewController()
vc.loadViewIfNeeded()
  

输出:SomeViewController

答案 2 :(得分:0)

您可以自己编写一个UIViewController子类,重写viewDidAppear方法,并使用以下代码:

   override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("Shown viewcontroller " + String(describing: type(of: self)))
        // (do whatever)
    }

然后,从其余的类中继承该类。