【发布时间】:2018-10-10 18:34:07
【问题描述】:
我有一个带有以下(静态)tableView 的 viewController:
class viewController: UIViewController, UITableViewDelegate {
private let tableView: UITableView = {
let tv = UITableView()
tv.separatorStyle = .singleLine
tv.allowsSelection = true
tv.isScrollEnabled = false
return tv
}()
private let tableData = ["row1", "row2", "row3", "row4"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.tableFooterView = UIView()
view.addSubview(tableView)
NSLayoutConstraints.activate([
tableView.centerXAnchor.constraints(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
tableView.centerYAnchor.constraints(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
)]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
cell.textLabel!.text = tableData[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
}
当我运行应用程序时,这个 viewController 显示一个空白屏幕。我知道我设置 tableview 约束的方式是问题所在,因为当我使用 topAnchor、bottomAnchor、leftAnchor 和 rightAnchor(以及其他一些调整)设置 tableView 时,会出现 tableview。知道为什么应用会这样吗?
【问题讨论】:
-
你还没有实现
UITableViewDataSource而不是numberOfRowsInSection函数。您需要四个约束来描述视图所需的位置和空间。 -
我不认为在这里实现
UITableViewDataSource是必需的,因为这是一个静态tableView(因此我的数据源只是tableData数组)。我也不需要显式定义numberOfRowsInSection,因为它是从我的 tableData 数组的长度中隐式检索的。 -
但是,我应该让你知道,在我的实际文件中,我确实实现了
numberOfRowsInsection。我会相应地编辑帖子。 -
当然表格需要知道要显示多少行。 numberOfRowsInsection
-
你绝对需要实现
UITableViewDataSource。你在这里只有一个随机数组实例变量和两个随机方法,它们恰好具有与UITableViewDataSource所需的签名相同的签名。你没有告诉UITableView使用你的视图控制器来获取它的信息,这正是需要的。如果不在表上设置数据源,只需实现这些功能就没有任何作用。如果您在这些函数中放置断点,则永远不会调用它们。
标签: ios swift autolayout tableview