为什么在viewWillAppear()中声明的变量无法从其子表视图的heightForRowAt中访问?

时间:2017-02-06 02:31:19

标签: ios uitableview uiviewcontroller

我的应用视图层次结构是我在其中使用UIViewController和UITableView。

我在我的UIViewController的override func viewWillAppear(_:)中声明并初始化一个变量。

但是,当我尝试在tableView(_:heightForRowAt:)中使用该变量时,我无法访问它(UIViewController没有以我在viewWillAppear(_:)中命名变量的方式命名的成员)。

即使我直接在UIViewController范围内声明有问题的变量,然后只在viewWillAppear(_:)中填充它,该变量也可以在所有范围内访问,但我不能在{{{ 1}},因为变量永远不会在该点之前填充。

任何人都可以帮我找出原因吗?

父UIViewController的tableView(_:heightForRowAt:)与其子UITableView的viewWillAppear(_:)之间的关系是什么?

示例#1:

tableView(_:heightForRowAt:)

示例#2:

class ListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
...
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    var rowHeights = Array<CGFloat?>(repeating: nil, count: myObject.childList.count)
    ...
    }
...
}
...
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
...
    if self.rowHeights[counter] == nil { // ERROR: self has no member named rowHeights
    ...
    }
...
}

1 个答案:

答案 0 :(得分:0)

在示例#1中,您在viewWillAppear函数上下文中本地声明了一个变量rowHeights。 I.o.w一旦你离开那个函数,该变量将不再存在。

实施例#2。
tableView是在调用viewWillAppear之前创建的 可能的解决方案:

  • 在设置rowHeights之后调用tableView.reloadData() viewWillAppear中。这将导致所有单元格再次调用cellforRow。
  • 在viewDidLoad()
  • 中设置rowHeights