首页 > 解决方案 > 难以在 swift 中为 tableview 附加数组数组

问题描述

我正在尝试从我拥有的一些数据中构建一个表格视图,但我遇到了一些我不理解的附加行为。

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

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

并在我的表格视图中显示它,我看到一个带有三行零的标题“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
    }

   
}

标签: iosarraysswifttableview

解决方案


当你这样做时:

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

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

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

var items:[[String]] = []

(只是一个空数组)


推荐阅读