Get class name of UIViewController in swift

后端 未结 9 827
野的像风
野的像风 2020-12-25 11:20

How to get class name of UIViewController Class in swift

In Objective C, we can do something like this :

self.appDelegate = (shAppDeleg         


        
相关标签:
9条回答
  • 2020-12-25 11:24

    A simple way in swift 3 is to write the below code:

    for instances:

    let className = String(describing: self)
    

    for classes:

    let className = String(describing: YourViewController.self)
    
    0 讨论(0)
  • 2020-12-25 11:26

    The property is called dynamicType in Swift.

    0 讨论(0)
  • 2020-12-25 11:29

    Expanding on juangdelvalle's answer.

    I added this as an extension so that it's reusable and easier to call from any view controller. Also in some cases NSStringFromClass in Swift returns a string in the format like this:

    < project name >.viewControllerClassName.

    This extension property is modified to get rid of the project name prefix and return only the class name.

    extension UIViewController {
        var className: String {
            NSStringFromClass(self.classForCoder).components(separatedBy: ".").last!
        }
    }
    
    0 讨论(0)
  • 2020-12-25 11:29

    Use String.init(describing: self.classForCoder)

    example:

    let viewControllerName = String.init(describing: self.classForCoder)
    print("ViewController Name: \(viewControllerName)")
    
    0 讨论(0)
  • 2020-12-25 11:32

    The cleanest way without needing to know the name of your class is like this.

    let name = String(describing: type(of: self))
    
    0 讨论(0)
  • 2020-12-25 11:37

    How about:

        extension NSObject {
    
        static var stringFromType: String? {
            return NSStringFromClass(self).components(separatedBy: ".").last
        }
    
        var stringFromInstance: String? {
            return NSStringFromClass(type(of: self)).components(separatedBy: ".").last
        }
    }
    
    0 讨论(0)
提交回复
热议问题