Swift - 在扩展中获取类名?

时间:2015-01-11 17:47:41

标签: swift

我试图从扩展中的类方法中获取类名。 这可能吗?我最终得到了" DRHT"作为班级的名称

扩展

extension UIViewController {

    public class func instanceFromStoryboard(storyboardIdentifier: String = "Main") -> UIViewController {
        let storyboard = UIStoryboard(name: storyboardIdentifier, bundle: nil)
        let controllerIdentifier = NSStringFromClass(self)
        return storyboard.instantiateViewControllerWithIdentifier(controllerIdentifier) as UIViewController
    }

}

用法

let homeViewController = HomeViewController.instanceFromStoryboard()

2 个答案:

答案 0 :(得分:1)

我最后做了不同的事情,以使其更加类型安全,并消除了铸造。

extension UIStoryboard {

    public class func instantiateViewController <T: UIViewController>(type: T.Type, storyboardIdentifier: String = "Main") -> T {
        let storyboard = UIStoryboard(name: storyboardIdentifier, bundle: nil)
        return storyboard.instantiateViewController(type)
    }

    public func instantiateViewController <T: UIViewController>(type: T.Type) -> T {
        return instantiateViewControllerWithIdentifier(String(type)) as! T
    }

}

extension UIViewController {

    public class func instantiateFromStoryboard(storyboardName: String = "Main") -> Self {
        return UIStoryboard.instantiateViewController(self, storyboardIdentifier: storyboardName)
    }
}

用法

let vc = UIStoryboard.instantiateViewController(HomeViewController.self)

let vc = UIStoryboard.instantiateViewController(HomeViewController.self, storyboardIdentifier: "Storybaord_Name")

let vc = storyboard.instantiateViewController(HomeViewController.self)

let vc = HomeViewController.instantiateViewController()

答案 1 :(得分:-1)

感谢MartinR和他的answer,我知道答案:

extension UIViewController
{
    class func instantiateFromStoryboard() -> Self
    {
        return instantiateFromStoryboardHelper(self, storyboardName: "Main")
    }

    class func instantiateFromStoryboard(storyboardName: String) -> Self
    {
        return instantiateFromStoryboardHelper(self, storyboardName: storyboardName)
    }

    private class func instantiateFromStoryboardHelper<T>(type: T.Type, storyboardName: String) -> T
    {
        var storyboardId = ""
        let components = "\(type.dynamicType)".componentsSeparatedByString(".")

        if components.count > 1
        {
            storyboardId = components[1]
        }
        let storyboad = UIStoryboard(name: storyboardName, bundle: nil)
        let controller = storyboad.instantiateViewControllerWithIdentifier(storyboardId) as! T

        return controller
    }
}

用法:

let vc = HomeViewController.instantiateFromStoryboard()