实现 UITableViewDataSource 方法的方式是否发生了变化?



最近 iOS 开发中可能发生了一些变化。 现在我们必须在 SceneDelegate 中设置窗口和根 VC,而不是 AppDelegate 的 didFinishLauching。(请不要故事板!好吧,这并不难,也没有那么不同。 但现在看来,我现在甚至无法在我的 UITableView数据源上取消单元格的排队。就这么简单!我又做错了什么?我将行数设置为 80 只是为了确保会出现一些东西,但那里没有运气。我在我的视图控制器(嵌入在导航控制器中(中获得了系统蓝绿色的表视图,仅此而已。有什么想法吗?

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let cellId = "cellId"
lazy var tableView: UITableView = {
let tb = UITableView()
tb.translatesAutoresizingMaskIntoConstraints = false
return tb
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemPink
setupTableView()
}
fileprivate func  setupTableView() {
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
tableView.backgroundColor = .systemTeal
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.widthAnchor.constraint(equalTo: view.widthAnchor),
tableView.heightAnchor.constraint(equalTo: view.heightAnchor)
])
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 80 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: cellId)!
cell.backgroundColor = .systemRed
cell.textLabel?.text = "cell: (indexPath.row)"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 50 }
func numberOfSections(in tableView: UITableView) -> Int { 1 }
}

除了设置委托之外,还应设置数据源:

tableView.dataSource = self

当您创建包含tableView(而不是UITableViewController(自定义ViewController时,您必须记住设置DataSource(如果需要,可以Delegate(。在这种情况下,获取委派和数据源的最佳位置之一是闭包:

lazy var tableView: UITableView = {
let tb = UITableView()
tb.dataSource = self
tb.delegate = self
tb.translatesAutoresizingMaskIntoConstraints = false
return tb
}()

相关内容

最新更新