objective-c - 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()
解决方案
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
推荐阅读
- angular - Angular 8:将表单标记为从父组件触摸
- flutter - sweepGradient 终点没有动画
- javascript - 我正在尝试在 electronjs 上打印页面,但是当我按照复制代码时它不会打印或给出任何错误
- c# - 使用 C# 从 Outlook 2016 电子邮件项目捕获或导入收件人、发件人、主题和电子邮件正文
- .net - 如何在特定应用程序上禁用 BrotliCompressionModule
- sql - 如何获取 PostgreSQL 表中的相关数据?
- javascript - 反应:Componentdidupdate,无法访问对象值
- r - 如何在 ggplot2 中为单个几何/颜色组合创建图例条目?
- google-apps-script - 谷歌表格脚本在最后一条记录之后复制并粘贴到另一张表格中
- xcode - no .xcodeproj file when downloading ZIP on github