如何以编程方式添加可重用的自定义视图? (Swift)
How to add reusable custom views programmatically? (Swift)
我创建了一个包含 table 的可重复使用的 xib 文件,它被加载到 TableView.swift
文件中,如下所示:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("TableView", owner: self, options: nil)
}
我提这个只是为了澄清我对如何加载 xib 文件并不感到困惑
我可以轻松地在我的 RootViewController.swift
文件中加载可重用视图,方法是向 UIViewController
添加视图并为该视图提供自定义 class,如下所示:
然后像这样为该视图创建出口:
所以这是我的问题:
为什么我不能像这样简单地添加视图:
let tableViewView = TableView()
当我这样做时,我得到一个我不完全理解的错误:
您还需要覆盖框架初始值设定项。
假设您的 TableView
class 是 UITableView
subclass,它应该看起来像这样:
class TableView: UITableView {
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
// any additional setup code
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// any additional setup code
}
}
因为您正试图以编程方式实例化 table 视图,所以您需要为其提供框架的初始化程序,而不仅仅是带有编码器的初始化程序。
我创建了一个包含 table 的可重复使用的 xib 文件,它被加载到 TableView.swift
文件中,如下所示:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("TableView", owner: self, options: nil)
}
我提这个只是为了澄清我对如何加载 xib 文件并不感到困惑
我可以轻松地在我的 RootViewController.swift
文件中加载可重用视图,方法是向 UIViewController
添加视图并为该视图提供自定义 class,如下所示:
然后像这样为该视图创建出口:
所以这是我的问题:
为什么我不能像这样简单地添加视图:
let tableViewView = TableView()
当我这样做时,我得到一个我不完全理解的错误:
您还需要覆盖框架初始值设定项。
假设您的 TableView
class 是 UITableView
subclass,它应该看起来像这样:
class TableView: UITableView {
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
// any additional setup code
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// any additional setup code
}
}
因为您正试图以编程方式实例化 table 视图,所以您需要为其提供框架的初始化程序,而不仅仅是带有编码器的初始化程序。