首页 > 解决方案 > Swift 中等效控制器的 self 类分配

问题描述

我在目标 c 中有一个具有方便功能的类 UIBaseClassViewController。现在我正在切换到 swift,我正在尝试将它的代码转换为 swift。给我问题的函数是

+(UIBaseClassViewController*)getController
{
   return [[[self class] alloc] initWithNibName:NSStringFromClass([self class]) bundle:[NSBundle mainBundle]];
}

我能够转换它,但它不能正常工作

static func getController() -> Self
{
    print("sam controller class = \(String(describing:self))")
    print("SAM controller = \(self.init(nibName: String(describing:self), bundle:Bundle.main))")

    return self.init(nibName: String(describing:self), bundle:Bundle.main)
}

输出:

sam controller class = UILoginViewController
SAM controller = <Swift_And_Node.UIBaseClassViewController: 0x7f8a4ee13830>

创建的对象是 UIBaseClassViewController 类型。它可以很好地加载笔尖,但由于对象是 UIBaseClassViewController 应用程序崩溃,因为它无法在 UILoginViewController 中的 UIBaseClassViewController 中找到函数。

在这种情况下,如何让它创建子类的对象而不是 parent.UILoginViewController

为了更好地理解显示添加代码:

UIBaseClassViewController

class UIBaseClassViewController: UIViewController {
static func getController() -> Self
{
    print("sam controller class = \(String(describing:self))")
    print("SAM controller = \(self.init(nibName: String(describing:self), bundle:Bundle.main))")
    var object = self
    return self.init(nibName: String(describing:self), bundle:Bundle.main)
}
}

UILoginViewController

class UILoginViewController: UIBaseClassViewController {}

3rd controller who need UILoginViewController:

UILoginViewController.getController()

标签: objective-cswiftclasssubclassbase-class

解决方案


You either have to call this static function on desired view controller class or not making it static at all. Please see the example below to see how it works in Swift.

class ParentView: UIView {
    static func printSelf() {
        print(String(describing: self))
    }
}
class ChildView: ParentView {}

ParentView.printSelf() // Prints ParentView
ChildView.printSelf() // Prints ChildView

推荐阅读