斯威夫特:房产“self.tableView”在super.init调用未初始化
问题描述:
我在斯威夫特的代码有一类设计UICollectionViewCells
斯威夫特:房产“self.tableView”在super.init调用未初始化
class PostCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {
let tableView: UITableView!
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellReuseIdentifier")
tableView.delegate = self
tableView.dataSource = self
designCell()
}
}
我需要在单元格中UITableView
因此,我加入UITableViewDelegate, UITableViewDataSource
类,但是这会返回以下错误
Property 'self.tableView' not initialized at super.init call
什么可能是问题,我该如何初始化tableView?
答
您需要可以创建和连接的UITableView
出口或创建编程
let tableView = UITableView(frame: yourFrame)
答
按照初始化规则所有存储的属性必须调用父类的方法init
之前被初始化。声明属性为隐式解包可选不会初始化该属性。
申报tableView
非可选的,super
呼叫
class PostCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {
let tableView: UITableView
override init(frame: CGRect) {
tableView = UITableView(frame: frame)
super.init(frame: frame)
backgroundColor = .white
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellReuseIdentifier")
tableView.delegate = self
tableView.dataSource = self
designCell()
}
}
谢谢你,你回答之前初始化 – sakoaskoaso