【发布时间】:2019-09-25 14:22:14
【问题描述】:
我想打印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
但它不是打印ViewController 的名称。
谢谢。
【问题讨论】:
-
let class_name = "\(HomeViewController.classForCoder())" -
let name = String(describing: type(of: self)) -
@AnuragSharma 它应该是“(self.classForCoder())”而不是“(HomeViewController.classForCoder())”,因为我是在 UIViewController 扩展中编写的。在这里,我正在尝试使用方法 swizzling 打印类名。
-
这……太矫枉过正了。如果你实现了,请分享。
-
@ManuMateos 是的,我做到了,你可以在你的项目中试试这个。我上面写的代码是正确的。