【问题标题】:tableView does not appear when centered into its parent viewtableView 在其父视图居中时不会出现
【发布时间】: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 约束的方式是问题所在,因为当我使用 topAnchorbottomAnchorleftAnchorrightAnchor(以及其他一些调整)设置 tableView 时,会出现 tableview。知道为什么应用会这样吗?

【问题讨论】:

  • 你还没有实现UITableViewDataSource而不是numberOfRowsInSection函数。您需要四个约束来描述视图所需的位置和空间。
  • 我不认为在这里实现UITableViewDataSource 是必需的,因为这是一个静态tableView(因此我的数据源只是tableData 数组)。我也不需要显式定义 numberOfRowsInSection,因为它是从我的 tableData 数组的长度中隐式检索的。
  • 但是,我应该让你知道,在我的实际文件中,我确实实现了numberOfRowsInsection。我会相应地编辑帖子。
  • 当然表格需要知道要显示多少行。 numberOfRowsInsection
  • 你绝对需要实现UITableViewDataSource。你在这里只有一个随机数组实例变量和两个随机方法,它们恰好具有与UITableViewDataSource 所需的签名相同的签名。你没有告诉UITableView 使用你的视图控制器来获取它的信息,这正是需要的。如果不在表上设置数据源,只需实现这些功能就没有任何作用。如果您在这些函数中放置断点,则永远不会调用它们。

标签: ios swift autolayout tableview


【解决方案1】:

您的表格视图可能在那里并且居中,但您没有定义大小,因此它可能被设置为零宽度和高度,这就是您看不到它的原因。

您可以通过将其宽度和高度的约束设置为常量或与其超级视图相关来解决此问题,具体取决于您想要的。

【讨论】:

  • 你说的很有道理。我尝试像这样添加宽度和高度锚:tableView.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor)tableView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor) 但它仍然没有出现!
【解决方案2】:

问题是这不是静态表格视图。如果是这样,你就不会实现cellForRowAt。它是一个普通的表视图,它需要一个数据源和委托。另外它需要一个高度和一个宽度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-17
    • 2014-09-17
    • 2011-02-08
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多