在swift for tableview中添加数组数组有困难



我正试图用我现有的一些数据构建一个表视图,但我遇到了一些附加我不理解的行为。

为了调试,我正在尝试这个,如果我说:

var sectionHeaders:[String] = ["0","1"]
var items:[[String]] = [["zero","zero","zero"],["one","one","one"]]

并在我的表视图中显示;0";具有三行零的另一个标题"0";1〃;其中三行";一";。这是意料之中的事。然而,如果我尝试使用append构建相同的结构,我会得到奇怪的结果:

var sectionHeaders:[String] = []
var items:[[String]] = [[]]
var tempItems:[String] = []
sectionHeaders.append("0")
tempItems.append("zero")
tempItems.append("zero")
tempItems.append("zero")
items.append(tempItems)
tempItems = []
sectionHeaders.append("1")
tempItems.append("one")
tempItems.append("one")
tempItems.append("one")
items.append(tempItems)

用这个,我得到一个";0";具有零行(无行(;1〃;具有三行零。

数据似乎在某种程度上被抵消了

我的附录有什么问题吗?

我的数据源委托非常简单:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

return sectionHeaders[section]
}


override func numberOfSections(in tableView: UITableView) -> Int {

return sectionHeaders.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return items[section].count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "testCell", for: indexPath)

let text = items[indexPath.section][indexPath.row]

cell.textLabel?.text = text

return cell
}

}

执行此操作时:

var items:[[String]] = [[]]

您将items定义为一个包含一个元素的数组(括号的外部集合(,该元素是一个空数组:[](括号的内部集合(。

为了不得到偏移,应该是这样的:

var items:[[String]] = []

(只是一个空数组(

最新更新