gpt4 book ai didi

Swift - 在扩展中获取类名?

转载 作者:行者123 更新时间:2023-11-28 09:15:23 25 4
gpt4 key购买 nike

我试图从扩展中的类方法中获取类名。这可能吗?我最终以“DRHT”作为类(class)名称

扩展

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()

最佳答案

我最终采用了不同的方式来使其更加类型安全并消除强制转换。

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()

关于Swift - 在扩展中获取类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27890152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com