Ios 在swift中获取UIViewController的类名

Ios 在swift中获取UIViewController的类名,ios,objective-c,uiviewcontroller,swift,Ios,Objective C,Uiviewcontroller,Swift,如何在swift中获取UIViewController类的类名 在目标C中,我们可以这样做: self.appDelegate = (shAppDelegate *)[[UIApplication sharedApplication] delegate]; UIViewController *last_screen = self.appDelegate.popScreens.lastObject ; if(last_screen.class != self.navigation

如何在swift中获取
UIViewController
类的类名

在目标C中,我们可以这样做:

self.appDelegate = (shAppDelegate *)[[UIApplication sharedApplication] delegate];
    UIViewController *last_screen = self.appDelegate.popScreens.lastObject ;

    if(last_screen.class != self.navigationController.visibleViewController.class){

    //.......

}
但在斯威夫特,我试着这样做

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let last_screen = appDelegate.popScreens?.lastObject as UIViewController
我不能这样做

if last_screen.class != self.navigationController.visibleViewController.class{

//....

}

没有
UIViewController
的类方法,即最后一个屏幕

该属性在Swift中被称为
dynamicType

要知道您的类名,您可以这样调用:

var className = NSStringFromClass(yourClass.classForCoder)

在juangdelvalle的基础上扩展

我将其作为扩展添加,以便它可以重用,并且更容易从任何视图控制器调用。在某些情况下,Swift中的
NSStringFromClass
会以如下格式返回字符串:

var className = NSStringFromClass(yourClass.classForCoder)
.viewControllerClassName

修改此扩展属性以除去项目名称前缀并仅返回类名

extension UIViewController {
    var className: String {
        NSStringFromClass(self.classForCoder).components(separatedBy: ".").last!
    }
}

这是伊苏鲁答案的快速版本

extension UIViewController {
    var className: String {
        return NSStringFromClass(self.classForCoder).components(separatedBy: ".").last!;
    }
}

swift 3中的一种简单方法是编写以下代码:

例如:

let className = String(describing: self)
课程:

let className = String(describing: YourViewController.self)

不需要知道类的名称的最干净的方法是这样的

let name = String(describing: type(of: self))
使用
String.init(描述:self.classForCoder)

例如:

let viewControllerName = String.init(describing: self.classForCoder)
print("ViewController Name: \(viewControllerName)")
斯威夫特4

假设我们有一个名为
HomeViewController
的类。然后,您可以使用以下代码获取类的名称:

let class_name = "\(HomeViewController.classForCoder())"
classForCoder()
方法返回
AnyClass
对象(您的类的名称),我们将其转换为字符串供用户使用。

如何:

    extension NSObject {

    static var stringFromType: String? {
        return NSStringFromClass(self).components(separatedBy: ".").last
    }

    var stringFromInstance: String? {
        return NSStringFromClass(type(of: self)).components(separatedBy: ".").last
    }
}

当你说“在某些情况下”,你的意思是它不会返回一个一致的答案吗?事实上,点前面的第一部分是模块名。因此,如果您的类是在外部库中定义的,您将看到模块名。最后一部分应该是真正的类名。除非苹果公司出于某种原因决定改变这个功能。为什么不直接使用呢让viewControllerName=“(viewControllerInstance.classForCoder())”``还有一个额外的';'最后。:)阿拉斯克。我想我不是一个心灵手巧的开发者。